有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何接受enter作为扫描仪的有效输入。nextLine()?

我只想让扫描器将新行读取为空字符串,然后在用户按enter键时继续下一个过程。所以有效输入必须是y,n,enter。你知道怎么做吗

这是我的代码:

String gender = "", employed = "";
Scanner in = new Scanner(System.in);
System.out.print("Gender M/F, press enter to skip... ");
while(!in.hasNext("[mfMF]$")){
    System.out.print("Invalid, please choose m/f only... ");
    in.nextLine();
}
if(in.hasNextLine()){
    gender = in.nextLine();
}
System.out.print("Employed? y/n, press enter to skip... ");
    while(!in.hasNext("[ynYN]$|")){
        System.out.print("Invalid, please choose y/n only... ");
        in.nextLine();
    }
if(in.hasNextLine()){
    employed = in.nextLine();
}
System.out.println(gender + " : " + employed);

共 (2) 个答案

  1. # 1 楼答案

    因此,要检查用户是否按了enter键,必须使用isEmpty()方法。方法如下所示:

    String enter = in.nextLine();
    if (enter.isEmpty()) {
       // do what is needed
    }
    
  2. # 2 楼答案

    试试这个:

    import java.util.*;
    
    class Scanner1
    {
       public static void main(String args[])
       {
         Scanner sc=new Scanner(System.in);
         String s;
         do
         {
            s=sc.nextLine();
               if(!(s.equalsIgnoreCase("y")||s.equalsIgnoreCase("n")||s.equalsIgnoreCase("")))
            {
                System.out.println("Please Enter valid input");
            }
    
        }while(!(s.equalsIgnoreCase("y")||s.equalsIgnoreCase("n")||s.equalsIgnoreCase("")));
    
        }
    }