Write a static method named negativeSum() that accepts a string of text as a par
ID: 3805783 • Letter: W
Question
Write a static method named negativeSum() that accepts a string of text as a parameter from the standard console input stream. Assume that the text is a series of integers, and determine whether or not the cumulative sum starting from the first number is ever negative. The method should produce a message indicating whether or not a negative sum is possible and it should return true if a negative sum can be reached and false if it can't be reached. For example, if the string contains the following text,
"38 4 19 27 -15 3 4 19 38 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: no negative sum and would return false. If the text is the following, TT 14 7 10 9 -18 10 17 42 98 the method finds that a negative sum is reached after adding 6 numbers together (14 7 10 9 18 10) and that the sum is 8. It should report the following: -8 after 6 steps and should return true, indicating that a negative sum can be reached. (3pts)Explanation / Answer
HI, Please find my implementtion.
Please let me know in case of any issue.
public class NegativeSum {
public static boolean negativeSum(String str){
//spliting str by space
String[] strArr = str.split("\s+"); // splitting by spaces
// getting int array
int[] arr = new int[strArr.length];
for(int i=0; i<arr.length; i++)
arr[i] = Integer.parseInt(strArr[i].trim());
int sum = 0;
for(int i=0; i<arr.length; i++){
sum = sum + arr[i];
if(sum < 0){
System.out.println(sum+" after "+(i+1)+" steps");
return true;
}
}
System.out.println("no negative sum");
return false;
}
public static void main(String[] args) {
String str1 = "38 4 19 -27 -15 -3 4 19 38";
String str2 = "14 7 -10 9 -18 -10 17 42 98";
System.out.println(str1+" : "+ negativeSum(str1));
System.out.println(str1+" : "+negativeSum(str2));
}
}
/*
Sample run:
no negative sum
38 4 19 -27 -15 -3 4 19 38 : false
-8 after 6 steps
38 4 19 -27 -15 -3 4 19 38 : true
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.