⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 readmanynumbers.java

📁 Java the UML Way 书中所有源码
💻 JAVA
字号:
/*
 * 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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -