問題描述
我正在嘗試解決一個作業(yè)(我對 Java 還是很陌生)并且已經(jīng)梳理了許多資源來解決這個沖突,但仍然無法解決這個問題.(注意:Tuna 是我的 Scanner 變量)
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);
}
}
}
結(jié)果是:線程main"java.lang.Error 中的異常:未解決的編譯問題:重復(fù)的局部變量計數(shù)
Result is: Exception in thread "main" java.lang.Error: Unresolved compilation problem: Duplicate local variable counted
我應(yīng)該解決的問題是:
編寫一個程序來讀入一個數(shù)字并將從 1 到該數(shù)字的所有數(shù)字相加.例如,如果用戶輸入6,則輸出為21(1+2+3+4+5+6).
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).
添加:我閱讀了一個相當(dāng)相似的 question(),但我之前聲明它并沒有犯 smae 錯誤.
ADDED: I read a question() that is rather similar but I did not make the smae mistake by declaring it before.
推薦答案
你在同一個作用域內(nèi)聲明了兩個同名變量:counted
在循環(huán)外和循環(huán)內(nèi)聲明.順便說一句,根據(jù)您的規(guī)范:
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:
編寫一個程序來讀入一個數(shù)字并將從 1 到該數(shù)字的所有數(shù)字相加.例如,如果用戶鍵入 6,則輸出為 21 (1+2+3+4+5+6)
您不需要第一個 counted
變量,因為它是一個常量(常量 1).因此,您可以通過這種方式將 1 聲明為常量:
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
然后在你的循環(huán)中使用這個常量:
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);
你可以在任何你想要的地方聲明你的變量.重要的是您在同一范圍內(nèi)聲明它們一次.您可以執(zhí)行以下操作:
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);
在循環(huán)外聲明 index
.結(jié)果不會改變.但是,將 for 循環(huán)
使用的變量聲明為索引是一種常見的做法(您可以將此變量稱為 index
或 counter
或i
或 mySisterIsCool
等)在 for 循環(huán)內(nèi)部(更準(zhǔn)確地說是在其保護(hù)中)以獲得更好的可讀性.
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.
這篇關(guān)于重復(fù)的局部變量(For循環(huán))的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!