英文:
Java "Type mismatch: cannot convert from int[][] to int" when returning copied array
问题
以下是你提供的代码的翻译部分:
我想创建一个返回复制数组的函数,但是我得到了以下错误:
在第10行出现“类型不匹配:无法将int[][]转换为int”,我不知道哪里出错了。
public class Usun {
public int[] newTable(int[][] table) {
int[] newTable[];
for (int i = 0; i <= table.length; i++) {
newTable[i] = table[i];
}
return newTable;
}
}
英文:
I wanted to make function that returns a copied array, but I'm getting this error:
> "Type mismatch: cannot convert from int[][] to int" on line 10,
and I don't know what is wrong.
public class Usun {
public int newTable(int[] table[]) {
int[] newTable[];
for (int i = 0; i <= table.length; i++) {
newTable[i] = table[i];
}
return newTable;
}
}
答案1
得分: 0
你想要返回一个整数数组 (int[]
) 而不是一个整数,此外,声明整数数组应该使用 int[] table
而不是 int[] table[]
。
另外,正如 @small_ticket 在他的评论中提到的,你必须初始化你的数组,否则你会得到 NullPointerException
,因为你将尝试向一个未初始化的数组中添加元素,这会导致编译时错误。
public class usun {
public int[] newTable(int[] table) {
int[] newTable = new int[table.length];
for (int i = 0; i < table.length; i++) {
newTable[i] = table[i];
}
return newTable;
}
}
英文:
you want to return an array of int (int[]
) not an int, also for declaring an array of int you use int[] table
and not int[] table[]
also, as @small_ticket mentioned in his comment, you have to initialize your array, or you will get NullPointerException
because you'll be trying to add elements to an uninitialized array, which results in compile time errors.
public class usun {
public int[] newTable(int[] table) {
int[] newTable = new int[table.length];
for (int i = 0; i < table.length; i++) {
newTable[i] = table[i];
}
return newTable;
}
}
答案2
得分: -1
"newTable"是一个二维数组。你尝试在你的方法中用返回类型为"int"的方式返回这个数组。
将你的函数的返回类型改为"int[][]"。此外,"newTable"在你的代码中没有被正确初始化。
另外,你可以使用内置的方法,比如"Arrays#copyOf"等,用于数组的深拷贝,这样你就不需要自己编写这些方法。
英文:
newTable
is an 2 dimensional array. You try to return this array in your method with a return type of int
.
Change the return type of your function to int[][]
. Also, newTable
is not properly initialized in your code.
In addition, you can use built-in methods like Arrays#copyOf
and so on for array deep copying as you don't have to write them yourself.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论