rojo rojo - 3 months ago 13
Java Question

trouble with char in java

I am practicing and I want to create a code with a infinite loop the while loop, but my problem is that I don't know how to compare char or read char from the keyboard. So, far I have done the code below, any suggestions please ?

Scanner keyboard = new Scanner(System.in);
System.out.println("Guess my favorite character: ");
String letter = keyboard.nextLine();
char secret = 'a';
while (true) {
System.out.println(" Enter guess:");
String guess = keyboard.nextLine();
for (int i = 0; i < guess.length(); i++) {

if (guess.chartAt(i).equals('a')) {
break;

}

}
System.out.println("YOU got it!");
}

}
}

Answer

Try like this;

String secret = "a";
Boolean isFounded = false;
while (true) {
    System.out.println(" Enter guess:");
    String guess = keyboard.nextLine();
    for (int i = 0; i < guess.length(); i++) {
         if (guess.equals(secret)) {
              System.out.println("YOU got it!"); 
              isFounded = true;
         }
         if(isFounded) break;
     }
     if(isFounded) break;
}