I'm trying to write a program that, after playing a game with the user, asks if they want to play again. For this test, I want to simply test the first letter of the word they input and if it's a "y" then the game will repeat.

at first, I had :

String repeat = "y";
String again = "y";

while ( repeat.charAt(0) == again.charAt(0)) {
    game();
    System.out.print("Would you like to play again?)"
    repeat = console.next();

}

but this wouldn't work if the user typed "Yes" for example, as Y != y.

I tried using the equalsIgnoreCase test but I couldn't figure it out. I tried doing:

String repeat = "y";
String again = "y";

while ( repeat.equalsIgnoreCase(again)) {
    game();
    System.out.print("Would you like to play again?)"
    String answer = console.next();
    repeat = answer.charAt(0);

}

but I kept getting "incompatible types" at:

repeat = answer.charAt(0);

Why won't java allow me to use charAt(0) in a string?


how can I go about fixing this?

Edited 6 Years Ago by akondray: n/a

akondray:

As jon said, Char object is not the same as String. Also, instead of trying to check the first char, why not check the whole words? You could use equalsIgnoreCase() method instead. You could take a look at String api also.

String repeat = "y";

while ( repeat.equalsIgnoreCase("y") || repeat.equalsIgnoreCase("yes")) {
    game();
    System.out.print("Would you like to play again?)"
    repeat = console.next();

}

Edited 6 Years Ago by Taywin: n/a

This article has been dead for over six months. Start a new discussion instead.