繁体   English   中英

从文件中只读取一行整数

[英]Read only one line of Integers from a file

我正在尝试读取包含整数的文件。 该文件有 40 行,每行有 80 个整数。 但是,当我运行以下代码时,我在每行中得到 40 行和 3200 个整数(它为每一行读取整个文件)。 我怎样才能解决这个问题。

    while(input.hasNextLine()){
        ++rows;
        Scanner colReader = new Scanner(input.nextLine());
        while(colReader.hasNextInt()){
            ++columns;
            colReader.nextInt();
        }
        colReader.close();
   }

因为你重复了循环,如果你想读取一个文件,你可以做下一个

BufferedReader bufferReader = new BufferedReader(new FileReader(new File("")));
        int line;
        StringBuilder stringBuilder = new StringBuilder();
        while ( (line =bufferReader.read()) != 0 ) {
           // Do something
        }

您还可以稍微简化您的代码。 您可以继续一一阅读整数。

Scanner input = new Scanner(new File("f:/numbs.txt"));
while (input.hasNextInt()) {
       int v = input.nextInt();
       System.out.println(v);
}


暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM