Java在空行后停止读取 [英] Java stop reading after empty line

查看:362
本文介绍了Java在空行后停止读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做学校运动,我无法想办法做一件事。
对于我读过的内容,Scanner不是最好的方法,但由于老师只使用Scanner,这必须使用Scanner完成。

I'm doing an school exercise and I can't figure how to do one thing. For what I've read, Scanner is not the best way but since the teacher only uses Scanner this must be done using Scanner.

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

This is the problem. The user will input text to an array. This array can go up to 10 lines and the user inputs ends with an empty line.

我做到了这一点:

 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++;        
    }

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

But this is not working properly and I can't figure it out. Ideally, if the user enters:

This is line one
This is line two

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

and now press enter, wen printing the array it should give:

[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

This reads two lines from your input: one which it compares to the empty string, then another to actually store in the array. You want to put the line in a variable so that you're checking and dealing with the same String in both cases:

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

这篇关于Java在空行后停止读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆