重复局部变量(For循环) [英] Duplicate local variable(For Loops)

查看:307
本文介绍了重复局部变量(For循环)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解决一个任务(我还对Java非常新),并且通过许多资源来梳理这个冲突,但仍然无法完全实现(注意:金枪鱼是我的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).

添加:我读了一个很相似的问题(),但是我没有通过以前声明这个错误。

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

推荐答案

在相同范围内声明具有相同名称的两个变量:计数被声明在循环之外和循环内。顺便说一句,根据你的规范:

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)

因为它是一个常数(常数1),所以需要第一个计数 var。你可以这样声明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循环用作索引的变量(您可以调用此变量 index 计数器 i mySisterIsCool 等)在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.

这篇关于重复局部变量(For循环)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆