Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

For this java program I want the user to guess a number from 1 to 10. The user s

ID: 3785838 • Letter: F

Question

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);

}

}

Explanation / Answer

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!

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote