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

Write a method named negativeSum that accepts a Scanner as a parameter reading i

ID: 3556719 • Letter: W

Question

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: 38 4 19 -27 -15 -3 4 19 38 None of these sums is negative, so the method would produce the following message and return false: no negative sum 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): 14 7 -10 9 -18 -10 17 42 98 It should output the following and return true, indicating that a negative sum can be reached: -8 after 6 steps

Explanation / Answer

for input file: 38 4 19 -27 -15 -3 4 19 38 Result will be; None of these sums is negative for input file 14 7 -10 9 -18 -10 17 42 98 Result will be negative sum can be reached:-8 after 6 steps import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.StringTokenizer; public class Test { public static void main(String arggs[]) { Test test = new Test(); String strFileName = "number.txt"; boolean flag = test.negativeSum(strFileName); } public boolean negativeSum(String strFileName) { String[] strLines = new String[10]; int lineNumber = 0; Scanner scanner; boolean flag = false; try { scanner = new Scanner(new File(strFileName)); while (scanner.hasNextLine()) { strLines[lineNumber] = scanner.nextLine(); ++lineNumber; } String temp = strLines[0]; StringTokenizer st = new StringTokenizer(temp); int sum = 0; int[] res = new int[20]; int count = 0; while (st.hasMoreTokens()) { sum = sum + Integer.parseInt(st.nextToken()); res[count] = sum; count++; } for (int i = 0; i
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote