【问题标题】:Read and calculate sum of integers from a file in Java [duplicate]从Java文件中读取并计算整数之和[重复]
【发布时间】:2015-11-14 18:20:31
【问题描述】:

假设我有一个简单的文本文件 Simple.txt 包含这样的数据

1 2 3 4 5 6

或

1 2 3 4 5

如何读取这个文件并使用 Java 打印整数的总和?

【问题讨论】:

标签: java io java-io


【解决方案1】:

试试这个代码。

import java.io.*;
import java.util.*;

public class SumNumbers {

public static void main(String args[]){
    try{
        File f = new File(args[0]);
        Scanner scanner = new Scanner(f);
        int sum = 0;
        while (scanner.hasNext()){
            sum += scanner.nextInt();
        }
        System.out.println("Sum:"+sum); 
    }catch(Exception err){
        err.printStackTrace();
    }

}
}

编辑:如果你想在文件中捕获不正确的输入,你可以改变 while 循环如下

         while (scanner.hasNext()){
            int num = 0;
            try{
                num = Integer.parseInt(scanner.nextLine());
            }catch(NumberFormatException ne){

            }
            sum += num;
        }

【讨论】:

  • 不,请不要使用 try-catch 来处理错误的输入类型。 Scanner 允许我们使用hasNextTYPE,所以让我们使用它。如果类型不正确,只需调用 has... 并使用 next 或 nextLine 使用不正确的值(如果我们想在不正确的值之后使用所有值)。
  • 在尝试访问其元素之前,您至少应该检查args 的长度;不要依赖用户提供正确的命令行参数。
【解决方案2】:

试试这个。

import java.util.*;
import java.io.File;
import java.io.IOException;

public class ReadFile
{
    public static void main(String[] args)
    throws IOException
    {
        Scanner textfile = new Scanner(new File("Simple.txt"));

        filereader(textfile);
}   


   static void filereader(Scanner textfile)     
{         
    int i = 0;         
    int sum = 0;          
    while(textfile.hasNextLine())         
    {       
        int nextInt = textfile.nextInt();          

        System.out.println(nextInt);             
        sum = sum + nextInt;
        i++;         
    }     
}

【讨论】:

  • 为什么是 while(i
  • 你必须使用while(textfile.hasNextLine())
  • 请您投票并接受我的回答。
猜你喜欢
  • 2018-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-08
相关资源
最近更新 更多