集册 Java实例教程 从文件中读取数字并使用扫描仪将其相加

从文件中读取数字并使用扫描仪将其相加

欢马劈雪     最近更新时间:2020-01-02 10:19:05

496
从文件中读取编号并使用扫描仪将其添加

import java.io.File;
/** 
 来自 n  o  w  j  a  v  a . c o m**/

import java.io.IOException;

import java.util.Scanner;


/**

 * This version of the program confirms that the

 * Numbers.txt file exists before opening it.

 */


public class FileSum2 {

  public static void main(String[] args) throws IOException {

    double sum = 0.0; // Accumulator, initialized to 0


    // Make sure the file exists.

    File file = new File("Numbers.txt");

    if (!file.exists()) {
    /*
    时 代 J a v a - N o w J a v a . c o m 提供
    */

      System.out.println("The file Numbers.txt is not found.");

      System.exit(0);

    }


    // Open the file for reading.

    Scanner inputFile = new Scanner(file);


    // Read all of the values from the file

    // and calculate their total.

    while (inputFile.hasNext()) {

      // Read a value from the file.

      double number = inputFile.nextDouble();


      System.out.println("Current number " + number);


      // Add the number to sum.

     
展开阅读全文