1

Assume I have a simple text file Simple.txt which contains data like this

1 2 3 4 5 6       

or

1
2
3
4
5       

how to read this file and print the sum of the integers using Java?

Enam Ahmed Shahaz
  • 195
  • 1
  • 2
  • 10

2 Answers2

1

try this.

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++;         
    }     
}
Saedawke
  • 461
  • 5
  • 18
1

Try this code.

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();
    }

}
}

EDIT: If you want to catch improper inputs in the file, you can change while loop as follows

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

            }
            sum += num;
        }
Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
  • 1
    No, please don't use try-catch to handle incorrect input types. Scanner allows us to use `hasNextTYPE` so lets use it instead. In case of incorrect type simply invoke `has...` and consume that incorrect value with `next` or `nextLine` (if we want to consume all values in line after incorrect one). – Pshemo Nov 14 '15 at 18:52
  • You should at least check the length of `args` before attempting to access its elements; don't rely on the user supplying the right command-line arguments. – jub0bs Nov 14 '15 at 18:54