Java空行后停止读取

Fav*_*las 5 java

我正在做学校运动,我无法想象如何做一件事.对于我所读到的,扫描仪不是最好的方法,但由于教师只使用扫描仪,这必须使用扫描仪完成.

这就是问题.用户将文本输入到数组.此数组最多可以有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++;        
    }
Run Code Online (Sandbox Code Playgroud)

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

This is line one
This is line two
Run Code Online (Sandbox Code Playgroud)

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

[This is line one, This is line two, null,null,null,null,null,null,null,null,null]
Run Code Online (Sandbox Code Playgroud)

你能帮助我吗?

Mar*_*ers 8

 while (!sc.nextLine().equals("")){
        text[i] = sc.nextLine();
        i++;        
 }
Run Code Online (Sandbox Code Playgroud)

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

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