此程序将创建10个整数的数组。然后将数组中的每个元素初始化为2。然后添加数组的每个元素以获取整个数组的总数。我们期望的答案是20。查看您是否可以更正以下代码以产生正确的解决方案。
我怎么会出现一个错误,说即使我在for
循环中进行了sum
可能没有初始化?
public class WarmUp_01_22_2014{
public static void main(String[] args){
int[] myArray = new int[12];
int total=0;
for (int i = 0; i < 10; i++){
myArray[i] = 2;
}
for (int i = 0; i < 12; i++){
int sum = 0;
int sum += myArray[i];
}
System.out.println("The sum of the numbers in the array is " + sum);
}
}//end class WarmUp_01_22_2014
您没有使用该代码收到该消息;这不会编译,因为sum
对println
看不到。最有可能的是,您在main
主体中会声明int sum
,然后在循环中声明另一个int sum
。您只想"创建"一次变量,然后只需为其分配值。
我怀疑您在程序中确实在使用total
;只需将第二个for
循环更改为:
for (int i = 0; i < 12; i++){
total += myArray[i]; // the variable "total" was created and set to zero above
}
public class WarmUp_01_22_2014{
public static void main(String[] args){
int[] myArray = new int[12];
int total=0;
int sum = 0;
for (int i = 0; i < 10; i++){
myArray[i] = 2;
}
for (int i = 0; i < 12; i++){
sum += myArray[i];
}
System.out.println("The sum of the numbers in the array is " + sum);
}
}//end class WarmUp_01_22_2014
应该工作。将您的变量更高地声明,以便可以通过println()方法访问它。
几件事:
- 大小的数组 10个整数表示您需要编写
new int[10]
而不是new int[12]
- 您声明了for循环的内部内部的
sum
,因此在循环之外无法访问它(因为没有保证它甚至会被声明)。 - 您还通过编写
int sum += myArray[i]
在每个循环中重新计算sum
-仅声明一次 -
i < 12
和i < 10
可以更改为i < myArray.length
,以使其更一般。
public class WarmUp_01_22_2014{
public static void main(String[] args){
int[] myArray = new int[10]; // size 10, not 12
int sum = 0; // declare sum here
for (int i = 0; i < myArray.length; i++){ // < myArray.length
myArray[i] = 2;
}
for (int i = 0; i < myArray.length; i++){ // < myArray.length
sum += myArray[i]; // add on to the sum, don't declare it here
}
System.out.println("The sum of the numbers in the array is " + sum);
}
}
如何解决问题
一个简单的调整,例如(i)在输入循环之前带上声明,以及(ii)使用变量sum
时更改值类型(int
),第二次避免冲突将有能力:
public class WarmUp_01_22_2014{
public static void main(String[] args) {
int[] myArray = new int[12];
int total = 0;
for (int i = 0; i < 10; i++) {
myArray[i] = 2;
}
//declare varaible here to avoid error
int sum = 0;
for (int i = 0; i < 12; i++) {
//change int sum+=myArray[i] to sum+=myArray[i]
sum += myArray[i];
}
System.out.println("The sum of the numbers in the array is " + sum);
}
}
推理
编译器编译源代码时,它仍然不知道像sum
这样的变量确实存在。根据编译器的说法,只有在激活for
循环时才创建变量sum
(我们作为人类所知道的是不可避免的,但机器不可避免)。