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);
}
}
You are asking for a number potentially twice in a loop. Once in the
ifblock, and once after yourelseblock. Without parentheses, only the first statement is the block. Instead ofTry
Also, your first number is added twice; remove the first addition from before the
whileloop.Additionally, while it's legal and it's possibly your actual requirements, this line
won't accept
1or100. It's possible your requirements would include accepting both1and100, in which case the condition should beNumber >= 1 && Number <= 100.Incidentally, conventionally Java variables start with a lowercase letter, while classes start with an uppercase letter, meaning that the variables
NumberandSumshould be renamednumberandsum, respectively.