Question: Read file input from Java program and return the sum of all ints in file. This is the code I have, result I get is

Read file input from Java program and return the sum of all ints in file. This is the code I have, result I get is file not found, 0. Can anyone fix this for me? Please DO NOT USE BufferedReader, this needs to be done with a scanner. I'm trying to get this set to where I can easily use a method to test my result (int=problem1Solution), but make it so that I can keep the testing method for other problems I have to do. This is what I have:

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class Problem1 {

public static void main(String[] args) {

new Problem1();

}

public Problem1() {

int problem1Solution = Problem(new File("Problem1.txt"));

System.out.println(problem1Solution);

}

public int Problem(File file) {

int sum = 0;

try {

Scanner fileInput = new Scanner(file);

while (fileInput.hasNextLine())

;

{

System.out.println(fileInput.nextLine());

sum = sum + fileInput.nextInt();

}

fileInput.close();

} catch (FileNotFoundException e) {

System.out.println("file not found");

}

return sum;

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!