我只是希望扫描程序将新行读为空字符串,然后如果用户按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);
答案 0 :(得分:0)
因此,要检查用户是否按下了enter,您必须使用 isEmpty()方法。这样做的方法如下所示:
String enter = in.nextLine();
if (enter.isEmpty()) {
// do what is needed
}
答案 1 :(得分:0)
试试这个:
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("")));
}
}