Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

java - Duplicate local variable(For Loops)

I'm trying to solve an assignment (I'm still very new to Java) and have combed through many resources to solve this conflict but still can't quite work it out.(NOTE: Tuna is my Scanner variable)

    int counted, sum, counted1;


    System.out.print("Enter your number to be calculated: ");
    counted = tuna.nextInt();
    counted1 =tuna.nextInt();


    for(int counted=0;counted<=counted1;counted++){
        System.out.println("The sum is: "+ counted);
    }
}

}

Result is: Exception in thread "main" java.lang.Error: Unresolved compilation problem: Duplicate local variable counted

The problem I am supposed to solve is:

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).

ADDED: I read a question() that is rather similar but I did not make the smae mistake by declaring it before.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...