Java While loop not adding correctly

607 views Asked by At

I can't figure out why this isn't adding up correctly each time it loops. There's also a problem with the while loop not outputting the sum when -9999 is typed in.

import java.util.*;
public class list 
{
   public static void main(String args []) 
   {
      Scanner sc = new Scanner(System.in);
      int Number, Sum = 0;
      System.out.println("Enter the list of whole numbers, terminate by -9999> ");
      Number = sc.nextInt();
      Sum += Number;
      while (Number != -9999) 
      {
         if (Number > 1 && Number < 100)
         {
            Sum += Number;
            Number = sc.nextInt();
         } 
         else
           System.out.println("Please enter a number between 1 and 100");
         Number = sc.nextInt();
      }
      System.out.println("Sum is " + Sum);
   }
}
2

There are 2 answers

2
rgettman On

You are asking for a number potentially twice in a loop. Once in the if block, and once after your else block. Without parentheses, only the first statement is the block. Instead of

else
    System.out.println("Please enter a number between 1 and 100");
  Number = sc.nextInt();

Try

else
{
    System.out.println("Please enter a number between 1 and 100");
    Number = sc.nextInt();
}

Also, your first number is added twice; remove the first addition from before the while loop.

Additionally, while it's legal and it's possibly your actual requirements, this line

if (Number > 1 && Number < 100)

won't accept 1 or 100. It's possible your requirements would include accepting both 1 and 100, in which case the condition should be Number >= 1 && Number <= 100.

Incidentally, conventionally Java variables start with a lowercase letter, while classes start with an uppercase letter, meaning that the variables Number and Sum should be renamed number and sum, respectively.

0
Yehia Awad On

1 Fixed When you are a planning to make a conditional loop better use do while()

2 There was a useless sc.nextInt() inside the if (Number >= 1 && Number <= 100) which was mixing up all your calculations

3 between 1 and 100 I suppose Number >= 1 && Number <= 100 is what you need unless you don't want the application to accept 1 and 100

Scanner sc = new Scanner(System.in);
            int Number, Sum = 0;
            System.out.println("Enter the list of whole numbers, terminate by -9999> ");
            Number = sc.nextInt();

           do {
              if (Number >= 1 && Number <= 100)
              {
               Sum += Number;
              } 
             else
                System.out.println("Please enter a number between 1 and 100");

              Number = sc.nextInt();
            } while (Number != -9999);
            System.out.println("Sum is " + Sum);
          }

Good Luck