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?
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?
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++;
}
}
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;
}