Java在空行后停止读取

我正在做学校运动,我无法想象如何做一件事。 对于我所读到的内容,Scanner不是最佳方式,但由于教师只使用Scanner,因此必须使用Scanner完成。

这就是问题。 用户将文本输入到数组。 此数组最多可以有10行,用户输入以空行结束。

我做到了这个:

String[] text = new String[11] Scanner sc = new Scanner(System.in); int i = 0; System.out.println("Please insert text:"); while (!sc.nextLine().equals("")){ text[i] = sc.nextLine(); i++; } 

但这不能正常工作,我无法弄明白。 理想情况下,如果用户输入:

 This is line one This is line two 

现在按回车键,打印它应该给出的数组:

 [This is line one, This is line two, null,null,null,null,null,null,null,null,null] 

你能帮助我吗?

  while (!sc.nextLine().equals("")){ text[i] = sc.nextLine(); i++; } 

这将从您的输入中读取两行:一行与空字符串进行比较,然后另一行与数组实际存储。 您希望将该行放在变量中,以便在两种情况下检查和处理相同的String

 while(true) { String nextLine = sc.nextLine(); if ( nextLine.equals("") ) { break; } text[i] = nextLine; i++; } 

这是适用于您的代码的典型readline惯用语:

 String[] text = new String[11] Scanner sc = new Scanner(System.in); int i = 0; String line; System.out.println("Please insert text:"); while (!(line = sc.nextLine()).equals("")){ text[i] = line; i++; }