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

So I just created a program that does EVERYTHING I wanted it to do: It scans a .

ID: 3835908 • Letter: S

Question

So I just created a program that does EVERYTHING I wanted it to do:

It scans a .txt file that I have containing the numbers "-5 2 6 -10 -1 8 -3 -19"

It does this perfectly, and gives me the sum of the numbers in the file

The problem is when I print out the "while" loop output it misses the number on the end (-19)

What am I doing wrong and how do I fix it to display all numbers???

negativesum java X 9 public class negative Sum 10 public static void mainCString args) 11 12 throws FileNotFoundException f 14 Scanner Input new Scanne Cnew File(''HW4Q3P2 P2.txt")); 15 16 int Kraft Input 17 18 int count 0; 19 20 int sum 0; 21 22 int G Kraft 23 24 while(Input has NextIntO 25 26 int Werk Input next IntO 27 28 System. out.print Kraft 29 30 Kraft Werk 31 32 sum sum Kraft 33 34 35 count++; 36 37 int Knucks sum G 38 39 40 ifCKnucks 001 System. out.printlnC"VnMnsum of Knucks after count steps" elset System. out.printlnC"VnInno negative sum"); 50 51 52 53 54 55 56 Problems Javadoc Declaration Console Kterminated negative Sum Java Application /Libraryl Java/JavavirtualMachinesijdk1.8.0-121.jdk/Contents/Home/bin/java (May 8 5 26 -10 1 8 sum of -22 after 7 steps

Explanation / Answer

The issue is that you are always printing the value of Kraft which you are assigining by the statement below

Kraft = Werk;

in each iteration of while loop. For last iteration, last value of Werk i.e. -19 is assigned to Kraft but not printed. So, the last element was not printing. I have corrected your code, and made the changes in bold.

negativeSum.java


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

public class nagativeSum {
   public static void main(String[] args) throws FileNotFoundException{
       Scanner Input = new Scanner(new File("HW4Q3P2.txt"));
       int Kraft = Input.nextInt();
       int count = 0;
       int sum = 0;
       int G = Kraft;
       while(Input.hasNextInt()) {
           int Werk = Input.nextInt();
           System.out.print(Kraft + " ");
           Kraft = Werk;
           sum = sum+Kraft;
           count++;
       }
       System.out.print(Kraft + " ");
       int Knucks = sum+G;
       if(Knucks<0) {
           System.out.println(" sum of "+Knucks+" after "+count+" steps");
       }
       else{
           System.out.println(" no negative sum.");
       }
   }
}

Sample Run: -

-5 2 6 -10 -1 8 -3 -19

sum of -22 after 7 steps

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