readmanynumbers.java

来自「Java the UML Way 书中所有源码」· Java 代码 · 共 53 行

JAVA
53
字号
/*
 * ReadManyNumbers.java   E.L. 2001-08-15
 *
 * Reads many lines of numbers, and adds them together.
 */

import java.util.*;
import java.io.*;
class ReadManyNumbers {
  public static void main(String[] args) {
    String fileName = "numberFile.txt";
    try { 
      FileReader connToFile = new FileReader(fileName);
      BufferedReader reader = new BufferedReader(connToFile);
      
      int sum = 0;
      try {
        String aLine = reader.readLine();
        while(aLine != null) {
          StringTokenizer text = new StringTokenizer(aLine);
          while (text.hasMoreTokens()) {
            String s = text.nextToken();
            int number = Integer.parseInt(s); // may throw NumberFormatException
            sum += number;
          }
          aLine = reader.readLine();
        }
      } catch (IOException e) {
        System.out.println("IO-Error when reading from file: " + fileName);
      } catch (NumberFormatException e) {
        System.out.println("Error when converting from text to number.");
      }
      reader.close();
      System.out.println("The sum of all the numbers is " + sum);
      
    } catch (FileNotFoundException e) {
      System.out.println("File not found: " + fileName);
    } catch (IOException e) {
      System.out.println("IO-Error when opening/closing the file: " + fileName);
    }
  }
}

/* Example Run:
Data file:
23 45 678 1 -56
-42 898 7
3 56 -90 0 67
4

Output:
The sum of all the numbers is 1594
*/

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?