2013-04-16 60 views
8

这可能是最简单的事情之一,但我没有看到我做错了什么。为什么nextLine()返回一个空字符串?

我的输入包含一个带有数字的第一行(要读取的行数),一堆带有数据的行以及只有\ n的最后一行。我应该处理这个输入,并在最后一行之后,做一些工作。

我有这个输入:

5 
test1 
test2 
test3 
test4 
test5 
     /*this is a \n*/ 

以及读取输入我有这样的代码。

int numberRegisters; 
String line; 

Scanner readInput = new Scanner(System.in); 

numberRegisters = readInput.nextInt(); 

while (!(line = readInput.nextLine()).isEmpty()) { 
    System.out.println(line + "<"); 
} 

我的问题是为什么我不打印任何东西?程序读取第一行,然后什么都不做。

+0

btw,不是第一个数字是测试的数量? – RiaD

+0

尝试用行!= null替换!line.isEmpty()? – user2147970

+0

是的,它是测试次数 – Favolas

回答

31

nextInt不会读取以下换行符,因此第一个nextLinewhich returns the rest of the current line)将始终返回一个空字符串。

这应该工作:

numberRegisters = readInput.nextInt(); 
readInput.nextLine(); 
while (!(line = readInput.nextLine()).isEmpty()) { 
    System.out.println(line + "<"); 
} 

但我的建议是不要用nextInt/nextDouble/next /等,因为任何人都试图保持代码(包括你自己)可能不知道的,或混合nextLine已经忘记了,上面的,所以可能会被上面的代码弄糊涂了。

所以我建议:

numberRegisters = Integer.parseInt(readInput.nextLine()); 

while (!(line = readInput.nextLine()).isEmpty()) { 
    System.out.println(line + "<"); 
} 
+0

该死! 。为什么会出现这种行为的解释? –

1

我想我以前已经看到这个问题。我认为你需要添加另一个readInput.nextLine()否则你只是在5结束之间读书,之后

int numberRegisters; 
String line; 

Scanner readInput = new Scanner(System.in); 

numberRegisters = readInput.nextInt(); 
readInput.nextLine(); 

while (!(line = readInput.nextLine()).isEmpty()) { 
    System.out.println(line + "<"); 
} 
0

\n其实它并不能完全回答这个问题(为什么你的代码是不是工作),但你可以使用下面的代码。

int n = Integer.parseInt(readInput.readLine()); 
for(int i = 0; i < n; ++i) { 
    String line = readInput().readLine(); 
    // use line here 
} 

对于我来说,更具可读性,甚至可能(在文件的结尾有额外的信息)

BTW节省您的时间在这种罕见的情况下,当测试用例是不正确的,看来你参加一些编程竞争。请注意,该扫描仪输入大量数据的速度可能会很慢。你可能会考虑使用BufferedReader可能StringTokenizer(在这项任务中不需要)

相关问题