Java扫描程序测试空行



我使用Scanner读取3行输入,前两行是字符串,最后一行是int。我遇到了一个问题,当第一行是空的,我不知道如何绕过它。我必须这样做:

String operation = sc.nextLine();
String line = sc.nextLine();
int index = sc.nextInt();
encrypt(operation,line,index);

但当第一行为空时,我会收到一条错误消息。我尝试了以下方法来强制循环,直到我得到一个非空的下一行,但它也不起作用:

while(sc.nextLine().isEmpty){
operation = sc.nextLine();}

有人有什么提示吗?

循环应该可以工作,尽管您实际上必须调用isEmpty方法,并且每次迭代只扫描一次

String operation = "";
do {
operation = sc.nextLine();
} while(operation.isEmpty());

你也可以使用sc.hasNextLine()来检查是否有

试试这个:

Scanner scanner = new Scanner(reader);
String firstNotEmptyLine = "";
while (scanner.hasNext() && firstNotEmptyLine.equals("")) {
firstNotEmptyLine = scanner.nextLine();
}
if (!scanner.hasNext()) {
System.err.println("This whole file is filled with empty lines! (or the file is just empty)");
return;
}
System.out.println(firstNotEmptyLine);

然后您可以读取此firstNotEmptyLine之后的其他两行。

请尝试一下。

Scanner sc = new Scanner(System.in);
String operation = null;
String line = null;
int index = 0;
while(sc.hasNext()) {
String nextLine = sc.nextLine().trim();
if(!nextLine.isEmpty()) {
operation = nextLine;
break;
}
}
while(sc.hasNext()) {
String nextLine = sc.nextLine().trim();
if(!nextLine.isEmpty()) {
line = nextLine;
break;
}
}
while(sc.hasNext()) {
String nextLine = sc.nextLine().trim();
if(!nextLine.isEmpty()) {
index = Integer.parseInt(nextLine);
break;
}
}
System.out.println(operation + " " + line + " " + index);
public static void main(String args[]){
Scanner sc = new Scanner(System.in);        
String operation = sc.nextLine();
String line = sc.nextLine();
int index = sc.nextInt();
test(operation,line,index);
}
public static void encrypt(String a,String b,int c){
System.out.println("first :"+a+" Second :"+b+" Third :"+c);
}

我看不出有任何错误。它编译得很好。

最新更新