#Attempting to read and add all integers from certain files.

1 messages · Page 1 of 1 (latest)

round belfry
#

I am using a method to read and add the sums of an individual file. I am just stuck on syntax of adding numbers in a file together.

public static int sumFileContents(String fileName) throws IOException {
FileInputStream myFile = new FileInputStream(fileName);
while (scnr.hasNextInt()) {
int sum = (whats the syntax here? int + next int + next int etc);
}
return sum;

versed crestBOT
#

This post has been reserved for your question.

Hey @round belfry! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

median saffron
#

You would need to declare the int before the while loop

#

Than you can use the += operator to add the current line value to the existing variable

round belfry
#

public static int sumFileContents(String fileName) throws IOException {
FileInputStream myFile = new FileInputStream(fileName);
int sum;
while (scnr.hasNextInt()) {
sum += scnr.nextInt();
}
return sum;
}

#

its just telling me that sum is no longer initialized now

mystic coral
#

Yeah, you need to give it a start value