javaif-statementinputequalscharat

Java - charAt(), equalsIgnoreCase, if statement testing?


What I want is no matter what the user inputs, if the first letter of their input is either a 'y' or 'n' regardless of case, it will print "game start".

I've tried equalsIgnoreCase() with the "letter" variable but it gives the error: char cannot be dereferenced. Any recommendations will be really appreciated on this! Thanks!

Scanner input = new Scanner(System.in);

System.out.println("Do you want to continue?");

String wesker = input.nextLine();
char letter = wesker.charAt(0);

 if(letter == 'y' || letter == 'p'){
     System.out.println("Game start");
 } else {
     System.out.println("Game over");
 }

Solution

  • equalsIgnoreCase can be used only by Strings. For your case, if you want to use that method, you can do this:

    Scanner input = new Scanner(System.in);
    String wesker = input.nextLine();
    String letter = wesker.substring(0,1);
    
    if(letter.equalsIgnoreCase("y") || letter.equalsIgnoreCase("n")){
        System.out.println("Game start");
    } else {
        System.out.println("Game over");
    }