繁体   English   中英

从文件中读取整数

[英]Read in integers from a file

该方法应该将行上的所有整数相加,以打印出结果,然后移至下一行。

当我运行该方法时,它将添加除行中最后一个整数以外的所有整数,除非它后面有空格。 无论是否存在空格,如何使它添加整数?

public static void addRows(String fileName) {
        int count = 0;
        int x;
        try {
            Scanner s = new Scanner(new File(fileName));
            s.useDelimiter("[ ]+");
            while (s.hasNext()) {
                if (s.hasNextInt()) {
                    x = s.nextInt();
                    count += x;
                    }

                else {
                    System.out.println(count);
                    count = 0;
                    s.nextLine();
                }
            }
            System.out.println(count);

        }
        catch(IOException e) {System.out.println("No File Found.");}
}

Sample Input:
1  2   3
1 2 3

Output:
3
6
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String input;

while ((input = reader.readLine()) != null) {
  int sum = 0;
  String[] fields = input.split("\\s");
  for (String field : fields) {
    try {
      sum += Integer.parseInt(field);
    } catch (NumberFormatException e) {
      // ignored
    }
  }

  System.out.println(sum);
}
        while (true) {
            if (s.hasNextInt()) {
                count += s.nextInt();
            } else if (s.hasNext()) {
                next();
            } else if (s.hasNextLine()) {
                s.nextLine();
            } else {
                break;
            }
        }

无论您如何定义定界符模式以及换行符是否可忽略,它都应该起作用。

一种选择是在行的末尾使用前瞻方式注册伪造的分隔符,而实际上不消耗\\ n:

s.useDelimiter("[ ]+|(?=\\n)");

使用定界符很难做到这一点。

尝试这段代码。 我已经对其进行了示例输入测试。 有用。

     public static void addRows(String fileName) 
    {
    int count = 0;
    int x;
    try 
     {

        Scanner s = new Scanner(new File(fileName));


        while (s.hasNextLine()) 
        {
          String line = s.nextLine(); // get the next line
          Scanner lineScanner = new Scanner (line); // get a new scanner for the next line! Done! Now proceed the usual way.

            while (lineScanner.hasNextInt()) 
               {
                  x = lineScanner.nextInt();
                  count += x;
               }

            System.out.println(count);
            count = 0;

        }


     }
    catch(IOException e) 
     {
         System.out.println("No File Found.");
     }
   }     

暂无
暂无

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

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