I’m trying to learn about the loops and the addition assignments such as ++, +=, *=… etc. The problem is I don’t get the logic of it completely if (x+=y = x + y).
Why in the sum= 0 the result is 6 and sum = number is 11? I don’t get where this 6 comes from. Do you know a nice resource to help me on this?
import java.util.Scanner;
public class RepeatingBreakingAndRemembering {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Give numbers:");
int number = Integer.valueOf(scanner.nextLine());
int sum = 0; // <------ Changing from sum = 0 to sum = number the result are 6 and 11
while (true){
number = Integer.valueOf(scanner.nextLine());
if (number == -1){
break;
}
sum += number; // sum = sum + number (0 + 5 + 2 + 4 = 11) <------ Shouldnt be like this?
//So why the result is 6?
}
System.out.println("Thx! Bye!");
System.out.println("Sum: " + sum);
}
}
I expected to happen a result of 11 when using the total sum starting at 0 instead I got a 6 and I don’t know where it comes from.
Lirzhan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2