I am creating this simple guessing game with three tries, but I need help adding code so it can display "First guess" followed by the integer the user puts in, "Second guess", etc... I currently just have "Enter your guess" which is the first try. What do I need to do? I'm confused on how to go about doing this. Sorry if the question is confusing.
import java.util.Scanner;
public class guess {
public static void main(String[] args) {
int randomN = (int) (Math.random() * 10) + 1;
Scanner input = new Scanner(System.in);
int guess;
System.out.println("Enter a number between 1 and 10.");
System.out.println();
int attempts = 0;
do {
attempts++;
System.out.print("Enter your guess: ");
guess = input.nextInt();
if (guess == randomN) {
System.out.println("You won!");
} else if (guess < 1 || guess > 10) {
System.out.println("out of range");
attempts = +1;
} else if (guess > randomN) {
System.out.println("Too high");
} else if (guess < randomN) {
System.out.println("Too low");
}
} while (guess != randomN && attempts < 3);
if (guess != randomN && attempts == 3) {
System.out.println("Number is " + randomN);
}
}
}
You could create another static method outside main
, where you can output a custom message depending on the attempts
.
public static String describe(int attempts) {
switch(attempts) {
case 1: return "First guess: ";
case 2: return "Second guess: ";
case 3: return "Third guess: ";
default: return "Enter your guess: "; //should not happen
}
}
Then in your main
use it like so:
...
do {
attempts++;
System.out.print(describe(attempts));
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.