public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
Random rnd = new Random();
boolean play = true;
int correctGue = 0;
char randChar = (char) ('a' + rnd.nextInt(26));
while (play ==true)
{
System.out.println(randChar);
System.out.println("I generated a random letter. Enter your guess:");
char guess = scan.next().charAt(0);
do
{
if((int)guess < (int)randChar)
{
System.out.println("The letter is later in the alphabet");
break;
}
else if((int)guess > (int)randChar)
{
System.out.println("The letter is earlier in the alphabet");
break;
}
}while (guess != randChar);
}
}
The problem im facing is the loops keeps on going when the user guesses the correct letter generated in char randChar = (char) ('a' + rnd.nextInt(26));, despite having the condition for loop to keep going as long as he/she get it incorrect while (guess != randChar); I would appreciate any help!
>Solution :
I fixed the code in the way I assume you wanted it to work. In there I show how you can exit outer loop from inside inner loops (mine is tagged outerLoopTag: in this case).
I also cleaned the code a bit to prevent crashing on invalid/empty data, and use a try-resource-catch on the Scanner to properly and easily clean that up too.
import java.util.Random;
import java.util.Scanner;
public class GuessRandomNumber {
public static void main(final String[] args) {
final Random rnd = new Random();
try (final Scanner scan = new Scanner(System.in);) {
outerLoopTag: while (true) {
final char randChar = (char) ('a' + rnd.nextInt(26));
while (true) {
System.out.println(randChar);
System.out.print("I generated a random letter. Enter your guess (enter . to exit): ");
final String line = scan.next();
if (line == null || line.trim().length() < 1) {
System.out.println("Invalid input, please retry!");
continue; // repeat inner loop
}
System.out.println("You entered '" + line + "'");
final char guess = line.charAt(0);
if (guess == '.') {
System.out.println("Game aborted, you entered '.'");
break outerLoopTag;
} else if (guess == randChar) {
System.out.println("You guessed the corret letter: " + guess + " and " + randChar);
break;
} else if (guess < randChar) {
System.out.println("The letter is later in the alphabet");
continue;
} else {
System.out.println("The letter is earlier in the alphabet");
continue;
}
}
}
}
}
}