Java 为什么nextLine()返回空字符串?

Java 为什么nextLine()返回空字符串?,java,Java,这可能是最简单的事情之一,但我看不出我做错了什么 我的输入包括一个带有数字(要读取的行数)的第一行、一组带有数据的行和一个只带有\n的最后一行。我应该处理这个输入,在最后一行之后,做一些工作 我有以下意见: 5 test1 test2 test3 test4 test5 /*this is a \n*/ 为了读取输入,我有这个代码 int numberRegisters; String line; Scanner readInput = new Scanner(System.in

这可能是最简单的事情之一,但我看不出我做错了什么

我的输入包括一个带有数字(要读取的行数)的第一行、一组带有数据的行和一个只带有\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 + "<");
}
整数寄存器;
弦线;
扫描仪读取输入=新扫描仪(System.in);
numberRegisters=readInput.nextInt();
而(!(line=readInput.nextLine()).isEmpty()){

System.out.println(line+“
nextInt
不读取以下新行字符,因此第一行
nextLine
()将始终返回空字符串

这应该起作用:

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

我想我以前见过这个问题。我想你需要添加另一个
readInput.nextLine()
,否则你只是在
5
的末尾和之后的
\n
之间阅读

int numberRegisters;
String line;

Scanner readInput = new Scanner(System.in);

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

while (!(line = readInput.nextLine()).isEmpty()) {
    System.out.println(line + "<");
}
整数寄存器;
弦线;
扫描仪读取输入=新扫描仪(System.in);
numberRegisters=readInput.nextInt();
readInput.nextLine();
而(!(line=readInput.nextLine()).isEmpty()){

System.out.println(line+“实际上它并不能完全回答这个问题(为什么您的代码不工作),但是您可以使用以下代码

int n = Integer.parseInt(readInput.readLine());
for(int i = 0; i < n; ++i) {
    String line = readInput().readLine();
    // use line here
}
int n=Integer.parseInt(readInput.readLine());
对于(int i=0;i
对我来说,它更具可读性,甚至可以在测试用例不正确的情况下节省您的时间(文件末尾有额外的信息)


BTW,看来你参加了一些编程竞赛。注意,扫描仪输入很多数据可能很慢。你可以考虑使用<代码> BufferedReader <代码>可能的<代码> StrugtoKeisher (不需要在这个任务中)

BTW,不是第一个数是测试次数吗?尝试替换!行!=null?是,它是tests@SamIam否<在结尾处,您可以先阅读此int x,然后再阅读第x行。有没有解释为什么会出现这种行为?
int n = Integer.parseInt(readInput.readLine());
for(int i = 0; i < n; ++i) {
    String line = readInput().readLine();
    // use line here
}