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

标签 java arrays input bufferedreader

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

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);

有什么建议吗?

最佳答案

您在循环内调用 readLine() 两次,并丢弃所有奇怪的结果。您需要分配 while 条件中获得的结果并在循环内使用它,而不是再次调用它。

关于java - 尝试使用 BufferedReader 从 System.in 读取输入并将其放入数组中,但似乎不想给我数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30271292/

相关文章:

java - 如何在java DatagramSocket中发送未实现Serialized接口(interface)的对象

java - 使用 .class 文件而不是 jar 将 Java 类导入 Jython

Java : Why can't I declare an array as a simple Object?

python - 如何允许用户输入各种各样的内容并让它们在 numpy 数组中工作?

java - "javax.swing.JPanel cannot be cast"异常,令人困惑

java - 为什么 xml 验证失败?

android - 使用 String ArrayAdapter 从字符串数组源填充 Listview

c - 热衷于将 TXT 文件转换为结构数组 - 段错误?

java - 如何用空格分隔用户输入

iPhone - 带有 html 内容的 UITextView?