Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I have literally no idea how to do this problem. If you manage to get it correct

ID: 3546937 • Letter: I

Question

I have literally no idea how to do this problem. If you manage to get it correctly please explain how each method was done. Thank You



Write a method named negativeSum that accepts a Scanner as a parameter reading input from a file containing a series of integers, and determine whether the sum starting from the first number is ever negative. The method should print a message indicating whether a negative sum is possible and should return true if a negative sum can be reached and false if not. For example, if the file contains the following text, your method will consider the sum of just one number (38), the sum of the first two numbers (38 + 4), the sum of the first three numbers (38 + 4 + 19), and so on up to the sum of all of the numbers:

None of these sums is negative, so the method would produce the following message and return false:

If the file instead contains the following numbers, the method finds that a negative sum of -8 is reached after adding 6 numbers together (14 + 7 + -10 + 9 + -18 + -10):

It should output the following and return true, indicating that a negative sum can be reached:

Explanation / Answer

There was a fair amount wrong with this. Curly braces in the wrong places, if else statements within the loop, declaring the scanner within the class method, instead of using the argument and declaring it with another class/main method...

Below I've done a quick mock up of a working solution. The entire thing is a ready to copy and paste Java class. It requires a .txt file called 'integer.txt' to be placed in the packages' directory. Please read through my comments above and try to take in what I've said, you were along the right kind of lines, but missing some key parts - the use of the Scanner argument being the most fundamental (there's no point having an argument if you're not going to use it!).

Anywayyyy...

=================================

package negativesummer;

import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.File;

public class NegativeSummer {

public static boolean negativeSum(Scanner line) throws FileNotFoundException {

int sum = 0;
int count = 0;

while (line.hasNextInt()) {

sum = sum + line.nextInt();
count++;

if (sum < 0) {
line.close();
System.out.println(sum + " after " + count + " steps");
return true;
}

}

line.close();
System.out.println("no negative sum");
return false;

}


public static void main(String[] args) throws FileNotFoundException {

File aFile = new File("integer.txt");

Scanner scn = new Scanner(aFile);

NegativeSummer test = new NegativeSummer();

test.negativeSum(scn);
}
}