这不是一个家庭作业问题。这是我的一种做法。请帮我理解我错在哪里。原来是静态void changeArray,但我把它改为static int changeArray并在最后插入一个return语句,但它仍然不会更新主代码。
公共课堂测试{
/*
* Change the method to also update the key at the main
*/
static int changeArray(int key, int array[]){
key = key + 7;
for (int i = 0; i < array.length; i++){
array[i] = array[i] + key;
}
System.out.println("*At changeArray *");
System.out.println("The key is: "+ key);
return key;
}
static void printArray(int array[]){
System.out.print("[ ");
for (int element:array){
System.out.print(element + " ");
}
System.out.println("]");
}
public static void main(String[] args){
int key = 5;
int[] array = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19};
System.out.println("*At the main *");
System.out.println("The key is: "+ key);
printArray(array);
changeArray(key, array);
System.out.println("*At the main *");
System.out.println("The key is: "+ key); <--- (this is supposed to be 12 after the method is called, but it keeps printing out 5)
printArray(array);
}
}
答案 0 :(得分:0)
您需要将main方法中的键变量设置为changeArray的返回值。由于key是基本类型,因此在changeArray方法中更改它不会在main方法中更改它。将changeArray调用更改为以下内容。 key = changeArray(key,array)