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. Also, please keep the public int Problem(File file) in tact, this is included in the initial answer I need to provide,. 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. I'd like to do this in another class if possible. Please explain thoroughly as I am really having trouble understanding passing arguements. 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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started