我写了一个java程序“Test”,它是:
class Get{
static void fIntarray(int[] b){
b = {10};
}
}
class Test{
public static void main(String[] args){
int[] a;
Get.fIntarray(a);
System.out.println(a[0]);
}
}
但是当我编译它时,编译器报告了以下错误:
Test.java:3: error: illegal start of expression
b = {10};
Test.java:3: error:not a statement
b = {10};
Test.java:3: error: ";" expected
b = {10};
Test.java:5: error: class, interface, or enum expected
}
我想创建一个整数数组a,并通过在Get类中传入方法fIntarray给数组a赋值10。我不知道哪里出错了?
答案 0 :(得分:1)
class Get{
static int[] fIntarray(){ // you don't need to pass an array as argument here
return new int[] {10};
}
}
class Test{
public static void main(String[] args){
int[] a;
a = Get.fIntarray(); // here you assign return value of Get.fIntarray() method to "a" array
System.out.println(a[0]);
}
}
您可能希望看到this question(如评论部分所示),以了解您尝试对数组进行的更改为何不生效。
答案 1 :(得分:0)
这个解决方案对你有用吗?
class Get{
static int[] fIntarray(int[] b){
b = new int[]{10};
return b;
}
}
class Test{
public static void main(String[] args){
int[] a = null;
a=Get.fIntarray(a);
System.out.println(a[0]);
}
}
答案 2 :(得分:0)
Java是pass-by-value,所以如果你在方法中重新分配数组b
,它就不会在外面改变传递的数组a
。
示例:
class Get{
static void fIntarray(int[] b){
b = new int[]{10}; // This will NOT be reflected on 'a'
}
}
class Test{
public static void main(String[] args){
int[] a = null; // 'a' needs to be initialized somehow, or else you get a compiler error.
Get.fIntarray(a);
System.out.println(a[0]); // Gives NullPointerException because 'a' was not affected by the method and is still null
}
}
如果希望在方法中填充数组,则需要在将其传递给该方法之前将其完全实例化。
class Get{
static void fIntarray(int[] b){
// Could potentially produce an ArrayIndexOutOfBoundsException if the array has length 0.
b[0] = 10;
}
}
class Test{
public static void main(String[] args){
int[] a = new int[1]; // Create an empty array with length 1.
Get.fIntarray(a);
System.out.println(a[0]); // Prints 10
}
}
答案 3 :(得分:-1)
您的错误是在数组初始化时,在java中我们使用类似的构造函数初始化数组:
int[] tab = new int[]{10,-2,12};
这是您案件的正确代码:
class Get{ static void fIntarray(int[] b){ b = new int[]{10};}}
希望它会有所帮助,祝你好运。