For this java program I want the user to guess a number from
For this java program I want the user to guess a number from 1 to 10. The user should have a limited amount of tries (3 times.) I, however, want to dispaly a message after the user has run out of tries saying (You lost.) How can I do that?
import java.util.Scanner;
public class ThirdHomework
{
public static void main(String[] args) {
int ActualNumber;
ActualNumber = (int) (Math.random() * 9 + 1);
Scanner keyboard = new Scanner(System.in);
int guess;
int tries = 0;
System.out.println(\"Please think of a number between 1 and 10\");
System.out.println();
do {
tries++;
System.out.print(\"Enter your guess: \");
guess = keyboard.nextInt();
if (guess == ActualNumber)
System.out.println(\"You won!\");
else if (guess < ActualNumber)
System.out
.println(\"No, my number is bigger\");
else if (guess > ActualNumber)
System.out
.println(\"No, my number is smaller\");
} while (guess != ActualNumber && tries < 3);
}
}
Solution
Hi,
I have updated the code and highlighted the code changes below
ThirdHomework.java
import java.util.Scanner;
public class ThirdHomework
{
public static void main(String[] args) {
int ActualNumber;
ActualNumber = (int) (Math.random() * 9 + 1);
Scanner keyboard = new Scanner(System.in);
int guess;
int tries = 0;
System.out.println(\"Please think of a number between 1 and 10\");
System.out.println();
do {
tries++;
System.out.print(\"Enter your guess: \");
guess = keyboard.nextInt();
if (guess == ActualNumber)
System.out.println(\"You won!\");
else if (guess < ActualNumber)
System.out
.println(\"No, my number is bigger\");
else if (guess > ActualNumber)
System.out
.println(\"No, my number is smaller\");
} while (guess != ActualNumber && tries < 3);
if (guess != ActualNumber){
System.out.println(\"You lost!\");
}
}
}
Output:
Please think of a number between 1 and 10
Enter your guess: 8
No, my number is smaller
Enter your guess: 4
No, my number is smaller
Enter your guess: 5
No, my number is smaller
You lost!

