You are declaring two variables with the same name in the same scope: counted
is declared outside the loop and inside the loop. By the way, according to your specification:
Write a program to read in a number and sum up all the numbers from 1 to that number. For e.g, if the user key in 6, then the output is 21 (1+2+3+4+5+6)
you don't need the first counted
var, because it is a constant (the constant 1). You can, so, declare 1 as a constant this way:
final int STARTING_NUMBER = 1
and then use this constant in your loop:
int counted, sum;
counted = tuna.nextInt();
for(int index=STARTING_NUMBER;index<=counted;index++){
sum=sum+index;
}
System.out.println("The sum is: "+ sum);
EDIT: you can declare your variables wherever you want. The important is that you declare them once in the same scope. You can do something like:
int counted, sum, index;
counted = tuna.nextInt();
for(index=STARTING_NUMBER;index<=counted;index++){
sum=sum+index;
}
System.out.println("The sum is: "+ sum);
declaring index
outside the loop. The result won't change. It is a common pratice, though, to declare the variable that the for loop
uses as index (you can call this variable index
or counter
or i
or mySisterIsCool
and so on) inside the for loop itself (in its guard, to be more precise) for a better readability.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…