Command for inequality of char I want to ask the user about whether he wants to continue playing or not. For this I have used,

char choice; 
do
{
     System.out.println("Would you like to continue?(y/n)");
     choice=sc.nextLine().charAt(0);
     if (choice!='y' &amp;&amp; choice!='n')  
     {  
           System.out.println("Invalid Entry");
     }
}while (choice!='y' &amp;&amp; choice!='n');


This is working fine and I didn't face any issues, but is that the right way?
There are some minor issues with this:


The condition to check the value of choice is duplicated
The program will crash if the input is empty
The variable choice is declared outside the loop body
The formatting is a bit unusual


I suggest this way instead:

while (true) {
    System.out.println("Would you like to continue?(y/n)");
    String line = sc.nextLine();
    if (!line.isEmpty()) {
        char choice = line.charAt(0);
        if (choice == 'y' || choice == 'n') {  
            return choice;
        }
    }
    System.out.println("Invalid Entry");
}