重复的局部变量(For循环)

2022-01-10 00:00:00 variables duplicates local java

我正在尝试解决一个作业(我对 Java 还是很陌生)并且已经梳理了许多资源来解决这个冲突,但仍然无法解决这个问题.(注意: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);
    }
}

}

结果是:线程main"java.lang.Error 中的异常:未解决的编译问题:重复的局部变量计数

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

我应该解决的问题是:

编写一个程序来读入一个数字并将从 1 到该数字的所有数字相加.例如,如果用户输入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).

添加:我阅读了一个相当相似的 question(),但我之前声明它并没有犯 smae 错误.

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

推荐答案

你在同一个作用域内声明了两个同名变量:counted在循环外和循环内声明.顺便说一句,根据您的规范:

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:

编写一个程序来读入一个数字并将从 1 到该数字的所有数字相加.例如,如果用户键入 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

然后在你的循环中使用这个常量:

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

你可以在任何你想要的地方声明你的变量.重要的是您在同一范围内声明它们一次.您可以执行以下操作:

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

在循环外声明 index.结果不会改变.但是,将 for 循环 使用的变量声明为索引是一种常见的做法(您可以将此变量称为 indexcounterimySisterIsCool 等)在 for 循环内部(更准确地说是在其保护中)以获得更好的可读性.

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.

相关文章