需要我的java代码的帮助吗
我编写了一个java程序“Test”,它是:需要我的java代码的帮助吗,java,Java,我编写了一个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]); } } 但当我编译它时,编译器
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给数组a值10。我不知道哪里出了问题?这个解决方案适合您吗
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]);
}
}
您可能希望查看(如注释部分所建议的)以了解为什么您尝试对数组所做的更改无法生效。您的错误在于数组初始化,在java中,我们使用以下构造函数初始化数组:
int[]tab=newint[]{10,-2,12}代码>
这是您案例的正确代码:
class Get{static void fIntarray(int[]b){b=new int[]{10};}}}
希望它会有帮助,祝你好运。Java是,因此如果你在方法内部重新分配数组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
}
}
b={10}
只能用于声明tryb=newint[]{10}你可以写b=newint[]{10}代码>但这仍然不能满足您的需要,因为在Java中参数是按值传递的-将新值赋给b
不会改变a
。它是有效的。但是为什么我没有将a的指针指定给fIntarray,并在方法中更改a指向的位置呢?@Victoria读到:它可以工作,但会产生警告。在这种情况下,您不需要将任何参数传递给fIntarray方法。我还想写一个带参数的方法,但我还没有弄明白。@Victoria当我准备答案时,我没有寻找其他人的答案。无论如何,我发现我们的解决方案有些不同。我的意思是,我已经用这种方式编写了代码,我想使用另一种方法,其中的参数包含在方法中,您甚至不需要用null初始化数组。@Victoria参数在这里不需要fIntarray()
仅用于提供/返回包含一个元素的数组。您只需要将此返回值分配给数组。如果要在与要将此返回值赋给的数组相同的类中创建fIntarray()
,则将此数组作为参数传递会更有意义。
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
}
}