Use the Scanner class to read the characters entered by the user.
Use variables to store whether the characters entered by the user are correct.
Use the loop structure to prompt the user for input in the loop body and judge whether the characters entered by the user are correct.
If the characters entered by the user are incorrect, the system will prompt the user to re-enter. If the characters entered by the user are correct, the loop is exited.
Use reading characters outside the loop.
Here is a sample code:
Import java.util.scanner;
Public class Main {
Public static void main(String[] args) {
Scanner scanner = new scanner (system. in);
Boolean isCorrect = false
Char input;
And (! isCorrect) {
System.out.println ("Please enter a char:");
input = scanner.next()。 charAt(0);
if(input = = ' A ' | | input = = ' B ' | | input = = ' C '){
isCorrect = true
} Otherwise {
System.out.println ("Invalid input, please try again." );
}
}
System.out.println ("You have entered:"+input);
}
}
In this code, the user can only enter three characters, A, B or C. If the user enters other characters, the system will always prompt the user to re-enter.