简体   繁体   English

有没有办法验证回车键?

[英]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.用户需要多次输入 (y + press enter)。 If the user presses enter without (y), is there a way to validate the enter key?如果用户在没有 (y) 的情况下按下 Enter,有没有办法验证 Enter 键?

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.或者您可以使用开关盒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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