• Log in or sign up for an account here: https://www.sythe.org/login

Basic java while loop help please.

Looks like you are starting the count at 0 and incrementing upwards. How can you expect the loop to ever get to a negative number (-9999) if you are incrementing? I think what you want is:

sum-=sc.nextInt();

Unless you are inputting negative numbers..
 
Looks like you are starting the count at 0 and incrementing upwards. How can you expect the loop to ever get to a negative number (-9999) if you are incrementing? I think what you want is:

sum-=sc.nextInt();

Unless you are inputting negative numbers..

I just want to add a list of numbers, then the program to stop once I input -9999 and print out the sum.

Example:

1
5
6
8
9
-9999.

Sum = 29.
 
<3 n4n0
Discord Verified
Two Factor Authentication User
Community Participant
Spam Forum Participant
Sythe's 10th Anniversary
Sythe Awards 2011 Winner
Code:
Scanner sc = new Scanner(System.in);
int i=0;
double sum = 0.0;

System.out.println(" Enter a list of whole numbers, then type -9999 once your list is complete.");
i = sc.nextInt();
sum += i;

while(i!=-9999)
{
i = sc.nextInt();
sum += i;
}
System.out.println(" The sum is " + sum);

You were comparing i to -9999 but only setting i to the first input. You also never added the first input to your sum. Do you have questions with the above code (that should work but I didn't test it).
 
Code:
Scanner sc = new Scanner(System.in);
int i=0;
double sum = 0.0;

System.out.println(" Enter a list of whole numbers, then type -9999 once your list is complete.");
i = sc.nextInt();
sum += i;

while(i!=-9999)
{
i = sc.nextInt();
sum += i;
}
System.out.println(" The sum is " + sum);

You were comparing i to -9999 but only setting i to the first input. You also never added the first input to your sum. Do you have questions with the above code (that should work but I didn't test it).

Yeah, I just figured that out my self, thanks.. I've ended up using this;

while(i != -9999)
{
sum = sum + i;
i = sc.nextInt();
}
 
<3 n4n0
Discord Verified
Two Factor Authentication User
Community Participant
Spam Forum Participant
Sythe's 10th Anniversary
Sythe Awards 2011 Winner
Yeah, I just figured that out my self, thanks.. I've ended up using this;

while(i != -9999)
{
sum = sum + i;
i = sc.nextInt();
}

That works fine too!
 
duelarena.gg
Back
Top