




























































































Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Prepara i tuoi esami
Studia grazie alle numerose risorse presenti su Docsity
Prepara i tuoi esami con i documenti condivisi da studenti come te su Docsity
Trova i documenti specifici per gli esami della tua università
Preparati con lezioni e prove svolte basate sui programmi universitari!
Rispondi a reali domande d’esame e scopri la tua preparazione
Riassumi i tuoi documenti, fagli domande, convertili in quiz e mappe concettuali
Studia con prove svolte, tesine e consigli utili
Togliti ogni dubbio leggendo le risposte alle domande fatte da altri studenti come te
Esplora i documenti più scaricati per gli argomenti di studio più popolari
Ottieni i punti per scaricare
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Principali esercizi di Java dalle stringhe fino all´eredita´.
Tipologia: Esercizi
1 / 502
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!





























































































The classical introductory exercise. Just say "Hello, World!". "Hello, World!" is the traditional first program for beginning programming in a new language or environment. The objectives are simple: ● Modify the provided code so that it produces the string "Hello, World!". ● Run the test suite and make sure that it succeeds. ● Submit your solution and check it at the website. If everything goes well, you will be ready to fetch your first real exercise. Since this is your first Java exercise, we've included a detailed Tutorial that guides you through your solution. Check it out for tips and assistance! ● Introduction ● Exercise Structure ● Solving "Hello, World!" ● Step 1: Fix the solution ● Step 2: Run the tests ● Step 3: Submitting your first iteration ● Next steps Welcome to the first exercise on the Java track! This document is a step-by-step guide to solving this exercise. The instructions should work equally well on Windows, macOS and Linux. Even if you are already familiar with Java basics, stepping through this guide may be helpful as it will help you understand the output from the tool, Gradle, that we use to compile and test our code, as well as introduce some of the patterns common to all exercises in this track. When you fetch a new Java exercise, you will receive: ● one or more test files (always). These live in the src/test/java directory and define a set of tests that our solution must satisfy before we can safely declare that it is working.
● one or more starter files (initially). If provided, these live in the src/main/java directory and define shells of the classes you will need in order to solve the current problem. You can use our online editor to solve your solution and run the tests, but if you want to solve the problem and run tests locally check these links below: ● Installing Java and Gradle ● Working Locally ● Testing locally on the java track Either working locally or using the online editor, you should find the following code: String getGreeting() { return "Goodbye, Mars!"; } The objective is to modify the provided code so it produces the text "Hello, World!" instead of "Goodbye, Mars!". After making corrections and implementing your solution, run the tests again. You can run the tests using the online editor or locally on your machine: ● To run the tests in the online editor, click the "Run Tests" button. ● To run the tests locally, check Testing on the Java track If the tests fails, that's ok! See what the error message is telling you, change your code and test again. When your tests pass, move on to the next step. With a working solution that we've reviewed, we're ready to submit it to exercism.org. You can submit the solution using the online editor or locally using the Exercism CLI: ● To submit the exercise locally, first install the exercism CLI if you haven't already and then submit the files of your solution, e.g: $ exercism submit
Java is a statically-typed language, which means that the type of a variable is known at compile-time. Assigning a value to a name is referred to as defining a variable. A variable is defined by explicitly specifying its type. int explicitVar = 10; Updating a variable's value is done through the = operator. Here, = does not represent mathematical equality. It simply assigns a value to a variable. Once defined, a variable's type can never change. int count = 1; // Assign initial value count = 2; // Update to new value // Compiler error when assigning a different type // count = false; Java is an object-oriented language and requires all functions to be defined in a class. The class keyword is used to define a class. class Calculator { // ... } A function within a class is referred to as a method. Each method can have zero or more parameters. All parameters must be explicitly typed, there is no type inference for parameters. Similarly, the return type must also be made explicit. Values are returned from methods using
the return keyword. To allow a method to be called by other classes, the public access modifier must be added. class Calculator { public int add(int x, int y) { return x + y; } } Invoking/calling a method is done by specifying its class and method name and passing arguments for each of the method's parameters. int sum = new Calculator().add(1, 2); // here the "add" method has been called to perform the task of addition Scope in Java is defined between the { and } characters. Java supports two types of comments. Single line comments are preceded by // and multiline comments are inserted between /* and */. Instructions In this exercise you're going to write some code to help you cook a brilliant lasagna from your favorite cooking book. You have four tasks, all related to the time spent cooking the lasagna. Define the expectedMinutesInOven() method that does not take any parameters and returns how many minutes the lasagna should be in the oven. According to the cooking book, the expected oven time in minutes is 40: Lasagna lasagna = new Lasagna(); lasagna.expectedMinutesInOven(); // => 40 Define the remainingMinutesInOven() method that takes the actual minutes the lasagna has been in the oven as a parameter and returns how many minutes the lasagna still has to remain in the oven, based on the expected oven time in minutes from the previous task. Lasagna lasagna = new Lasagna(); lasagna.remainingMinutesInOven(30); // => 10
Booleans Booleans in Java are represented by the boolean type, which values can be either true or false. Java supports three boolean operators: ●! (NOT): negates the boolean ● && (AND): takes two booleans and results in true if they're both true ● || (OR): results in true if any of the two booleans is true Examples !true // => false !false // => true true && false // => false true && true // => true false || false // => false false || true // => true Instructions In this exercise, you'll be implementing the quest logic for a new RPG game a friend is developing. The game's main character is Annalyn, a brave girl with a fierce and loyal pet dog. Unfortunately, disaster strikes, as her best friend was kidnapped while searching for berries in the forest. Annalyn will try to find and free her best friend, optionally taking her dog with her on this quest. After some time spent following her best friend's trail, she finds the camp in which her best friend is imprisoned. It turns out there are two kidnappers: a mighty knight and a cunning archer. Having found the kidnappers, Annalyn considers which of the following actions she can engage in: ● Fast attack: a fast attack can be made if the knight is sleeping, as it takes time for him to get his armor on, so he will be vulnerable. ● Spy: the group can be spied upon if at least one of them is awake. Otherwise, spying is a waste of time. ● Signal prisoner: the prisoner can be signalled using bird sounds if the prisoner is awake and the archer is sleeping, as archers are trained in bird signaling, so they could intercept the message. ● Free prisoner : Annalyn can try sneaking into the camp to free the prisoner. This is a risky thing to do and can only succeed in one of two ways:
○ If Annalyn has her pet dog with her she can rescue the prisoner if the archer is asleep. The knight is scared of the dog and the archer will not have time to get ready before Annalyn and the prisoner can escape. ○ If Annalyn does not have her dog then she and the prisoner must be very sneaky! Annalyn can free the prisoner if the prisoner is awake and the knight and archer are both sleeping, but if the prisoner is sleeping they can't be rescued: the prisoner would be startled by Annalyn's sudden appearance and wake up the knight and archer. You have four tasks: to implement the logic for determining if the above actions are available based on the state of the three characters found in the forest and whether Annalyn's pet dog is present or not. Implement the ( static ) AnnalynsInfiltration.canFastAttack() method that takes a boolean value that indicates if the knight is awake. This method returns true if a fast attack can be made based on the state of the knight. Otherwise, returns false: boolean knightIsAwake = true; AnnalynsInfiltration.canFastAttack(knightIsAwake); // => false Implement the ( static ) AnnalynsInfiltration.canSpy() method that takes three boolean values, indicating if the knight, archer and the prisoner, respectively, are awake. The method returns true if the group can be spied upon, based on the state of the three characters. Otherwise, returns false: boolean knightIsAwake = false; boolean archerIsAwake = true; boolean prisonerIsAwake = false; AnnalynsInfiltration.canSpy(knightIsAwake, archerIsAwake, prisonerIsAwake); // => true Implement the ( static ) AnnalynsInfiltration.canSignalPrisoner() method that takes two boolean values, indicating if the archer and the prisoner, respectively, are awake. The method returns true if the prisoner can be signalled, based on the state of the two characters. Otherwise, returns false: boolean archerIsAwake = false; boolean prisonerIsAwake = true; AnnalynsInfiltration.canSignalPrisoner(archerIsAwake, prisonerIsAwake); // => true
Introduction Conditionals If Logical Operators Java supports the three logical operators && (AND), || (OR), and! (NOT). If statement The underlying type of any conditional operation is the boolean type, which can have the value of true or false. Conditionals are often used as flow control mechanisms to check for various conditions. For checking a particular case an if statement can be used, which executes its code if the underlying condition is true like this: int val; if(val == 9) { // conditional code } In scenarios involving more than one case many if statements can be chained together using the else if and else statements. if(val == 10) { // conditional code } else if(val == 17) { // conditional code } else { // executes when val is different from 10 and 17 } Switch statement Java also provides a switch statement for scenarios with multiple options. int val;
// switch statement on variable content switch(val) { case 1: // conditional code break; case 2: case 3: case 4: // conditional code break; default: // if all cases fail break; } Instructions In this exercise we will simulate the first turn of a Blackjack game. You will receive two cards and will be able to see the face up card of the dealer. All cards are represented using a string such as "ace", "king", "three", "two", etc. The values of each card are: card value card value ace 11 eight 8 two 2 nine 9 three 3 ten 10 four 4 jack 10 five 5 queen 10 six 6 king 10 seven 7 other 0 Note : Commonly, aces can take the value of 1 or 11 but for simplicity we will assume that they can only take the value of 11. Depending on your two cards and the card of the dealer, there is a strategy for the first turn of the game, in which you have the following options:
Implement a function that returns the string representation of a decision given your cards. This function is only called if the handScore is less than 21. It will receive 2 arguments: handScore and dealerScore. It should implement the bulletpoints in the category "Small Hand" above. handScore = 15 dealerScore = 12 SmallHand(handScore, dealerScore) // returns "H" public class Blackjack { public int parseCard(String card) { switch(card) { case "two": return 2; case "three": return 3; case "four": return 4; case "five": return 5; case "six": return 6; case "seven": return 7; case "eight": return 8; case "nine": return 9; case "ten": case "jack": case "queen": case "king": return 10; case "ace": return 11; default: return 0; } } public boolean isBlackjack(String card1, String card2) { return (parseCard(card1)+ parseCard(card2) == 21); }
public String largeHand(boolean isBlackjack, int dealerScore) { if (isBlackjack== true){ if (dealerScore<10){ return "W";} else {return "S";} } else {return "P";} } public String smallHand(int handScore, int dealerScore) { if(handScore<21 && handScore>=17 || handScore >=12 && handScore<=16 && dealerScore<=6){ return "S"; } else {return "H";} } // FirstTurn returns the semi-optimal decision for the first turn, given the cards of the player and the dealer. // This function is already implemented and does not need to be edited. It pulls the other functions together in a // complete decision tree for the first turn. public String firstTurn(String card1, String card2, String dealerCard) { int handScore = parseCard(card1) + parseCard(card2); int dealerScore = parseCard(dealerCard); if (20 < handScore) { return largeHand(isBlackjack(card1, card2), dealerScore); } else { return smallHand(handScore, dealerScore); } } } SUGGESTIONS: Congratulations on passing all the tests! ● I like the use of a switch. Another approach could use a HashSet with contains for the face card (and ten card) names and return 10 if card is in there. If not, then the value could be looked up from a Map with get. The Map could be populated with Map.of.
public int parseCard(String card) { if (faceCards.contains(card)) return 10; return cardVals.get(card); } public boolean isBlackjack(String card1, String card2) { return parseCard(card1) + parseCard(card2) == 21; } public String largeHand(boolean isBlackjack, int dealerScore) { if (!isBlackjack) return split; switch (dealerScore) {
case 10, 11: return stand; default: return win; } } public String smallHand(int handScore, int dealerScore) { if (handScore > 16) return stand; if (handScore < 12 || dealerScore > 6) return hit; return stand; } public String firstTurn(String card1, String card2, String dealerCard) { int handScore = parseCard(card1) + parseCard(card2); int dealerScore = parseCard(dealerCard); if (20 < handScore) return largeHand(isBlackjack(card1, card2), dealerScore); return smallHand(handScore, dealerScore); } }
One for you, one for me. Zaphod One for Zaphod, one for me. Before you start, make sure you understand how to write code that can pass the test cases. For more context, check out this tutorial. Most Java exercises include multiple test cases. These cases are structured to support a useful process known as test-driven development (TDD). TDD involves repeating a structured cycle that helps programmers build complex functionality piece by piece rather than all at once. That cycle can be described as follows:
return "One for you, one for me."; else {return "One for " + name + ", one for me.";} } } }
Introduction The way we measure time is kind of messy. We have 60 seconds in a minute, and 60 minutes in an hour. This comes from ancient Babylon, where they used 60 as the basis for their number system. We have 24 hours in a day, 7 days in a week, and how many days in a month? Well, for days in a month it depends not only on which month it is, but also on what type of calendar is used in the country you live in. What if, instead, we only use seconds to express time intervals? Then we can use metric system prefixes for writing large numbers of seconds in more easily comprehensible quantities. ● A food recipe might explain that you need to let the brownies cook in the oven for two kiloseconds (that's two thousand seconds). ● Perhaps you and your family would travel to somewhere exotic for two megaseconds (that's two million seconds). ● And if you and your spouse were married for a thousand million seconds, you would celebrate your one gigasecond anniversary. Note If we ever colonize Mars or some other planet, measuring time is going to get even messier. If someone says "year" do they mean a year on Earth or a year on Mars? The idea for this exercise came from the science fiction novel "A Deepness in the Sky" by author Vernor Vinge. In it the author uses the metric system as the basis for time measurements. Instructions