0

我无法理解 Scanner 或者我应该说来自控制台的输入

public class Calculate {

    public static void main(String[] args) throws IOException {
        System.out.println("enter the lines");
        Scanner s = new Scanner(System.in);
         ArrayList<String> result = new ArrayList<String>();
         String line = "";
         while((line = s.nextLine()) != null) {
             result.add(line);
         }
         for(String ss : result){
             System.out.println(ss);
         }
    }
}

Console :
enter the lines
[Inputs on console:]
aa
bb
cc

当我在调试模式下运行时,字符串 aa 和 bb 被添加到 List 结果中,但是当从扫描仪读取 cc 时,它没有添加到 List 我不确定,我错过了什么。对我来说看起来很傻,但有些我无法思考我错过了什么

4

1 回答 1

0

这个(稍微)修改的代码按预期工作(您可以通过输入一个空字符串退出程序):

public static void main(String[] args) {
    System.out.println("enter the lines");
    Scanner s = new Scanner(System.in);
    ArrayList<String> result = new ArrayList<String>();
    String line = "";
    while ((line = s.nextLine()) != null) {
        if (line.isEmpty()) break;
        result.add(line);
    }
    for (String ss : result) {
        System.out.println(ss);
    }
}

它准确地输出输入的内容。

于 2013-07-30T15:18:40.303 回答