【问题标题】:java- use scanner to read in and process one piece of information at a timejava-使用扫描仪一次读取和处理一条信息
【发布时间】:2014-09-25 09:59:19
【问题描述】:

我正在尝试使用扫描仪一次读取多行输入。我认为我使用循环的方式或读取信息的方式有问题。输出数组中没有存储任何内容。我在代码中评论了我的问题。有人可以帮忙吗?谢谢!

        Scanner c = new Scanner (System.in);
        while (c.hasNextLine()){
            ArrayList <Integer> record= new ArrayList <Integer> (); // next time the while loop runs, I expect the list record to be initialized again 

            String numbers = c.nextLine();

            int n = Integer.parseInt(numbers);
            for (int i=0; i<n; i++){
                String info = c.nextLine();//then read the following n lines use for loop

                int length = info.length(); //get the length of each line
                record.add(length);
            }       

            putRecordinArray(record);//some other function to process each record(a block of several lines processed each time by the while loop)
          }
    //here I tried to print out the array A generated by other function, but nothing was stored. 
    }

【问题讨论】:

  • 那么问题出在putRecordInArray()方法上?

标签: java loops arraylist while-loop system.in


【解决方案1】:

您的 Arraylist 名称是 records,但您使用 record 调用它,即 records without the 's'。你have to add the 's'。 您的调用语句之一的示例。

record.add(length);

改为:

records.add(length);

还有:

putRecordinArray(record);

改为:

putRecordinArray(records);

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多