简体   繁体   中英

Is there a way to validate the enter key?

I'm trying to validate inputs from the user. The user needs to enter (y + press enter) many times. If the user presses enter without (y), is there a way to validate the enter key?

public static void getInput() {
  Scanner input = new Scanner(System.in);
  System.out.print("Press 'y' to continue, 'n' to exit: ");
  char c = input.nextLine().charAt(0);
  if (c == 'n') {
    System.out.println("Exiting");
    System.exit(0);
  }
  while (c != 'y') {
    System.out.println("Invalid input!");
    System.out.println("Press 'y' to continue, 'n' to exit: ");
    c = input.nextLine().charAt(0);
  }
  if (c == 'n') {
    System.out.println("Exiting");
    System.exit(0);
  }
}

Just check if the input line is empty:

String line = input.nextLine()
if(line.isEmpty())
  //handle no input

This might help.

    Scanner input = new Scanner(System.in);
    
    while(true){
        System.out.print("Press 'y' to continue, 'n' to exit: ");
        char c = input.nextLine().charAt(0);
        
        if(c == 'n'){
            System.out.println("Exiting...");
            break;
        }
        
        else if(c == 'y'){
            //call your method here
            //method();
            System.out.println("User has input Y");
            break;
        }
        
        else{
            System.out.println("Please enter a valid keyword");
        }
    }

Or you can use a switch case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM