Can someone please help me find what is wrong with my code below. The program is suppose to add all the input numbers except for the sentinel which is -1. What am i doing wrong?

import java.util.*;

public class InClassWork
{

   static Scanner console = new Scanner(System.in);

    public static void main (String[] args)
    {
      int total = 0;
      int number;

      do
      {
      number = console.nextInt();
      total = total + number;
      }

      while (number != -1);


    System.out.println("The sum of the numbers entered is " + total);
}
}

You add the number you enter to the total before the while checks if its value is -1.

you should start number at 0 like you do for total, and switch both lines in your do-while, this way, on the first run through it will add 0 to the total. and on everyother pass its gonna add the last number before asking a new one.

To be a little more logical, you should use a while loop instead and ask for 1 number input BEFORE the while loop, then in the loop add the number THEN ask a new one. But both loops will work that way.

Also ,

total = total + number;

and

total += number;

are the same! ;)

well you dont need the do while statement, the while statement will do the job correctly-verifying the variable before executing, where as the do while verfiys the value at the end of each execution. also incorporate the 'number = console.nextInt()' into your while statement that should fix it :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.