尝试使用BufferedReader从System.in读取输入并将其放入数组中,但似乎不想给我数组

时间:2015-05-16 02:40:34

标签: java arrays input bufferedreader

如标题中所述,我使用的是从System.in读取的BufferedReader,并将值放入字符串数组中。当我调用方法执行此操作时,我会尝试检查数组的长度,但是当我这样做时,没有任何内容被打印出来。

String s = "";
        BufferedReader io = new BufferedReader
                (new InputStreamReader(System.in));     //create a new BufferedReader using system input

        String line;                                    //will be changed to the next line in the input
        try                                             //required or we cant compile it because exceptions
        {
            s = io.readLine() + "_";    //get the first integer value, which is how many 
                                                        //  pieces of info we have to process
            while((line = io.readLine()) != null)       //read until the end of the file
            {   
                s += io.readLine() + "_";                       //add it to the ArrayList (may not be needed)
                //System.out.println("Added line to list");
                //System.out.println(line);
            }

            io.close();                                 //done with input, close the stream
        }
        catch (IOException e) 
        {
            e.printStackTrace();
        }

        return s.split("_");

然后我调用包含此代码的方法,但几乎没有打印出来:

 String[] input = readInput();


    System.out.println(input.length);

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

你在循环中两次调用readLine()并抛出每个奇数结果。您需要分配在while条件中获得的结果并在循环内使用它,而不是再次调用它。