[英]Need help of my java code
我寫了一個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賦予數組a。 我不知道哪里出了問題?
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]);
}
}
您可能希望看到此問題 (如“注釋”部分中的建議),以了解為什么嘗試對數組進行的更改未生效。
這個解決方案對您有用嗎?
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是按值傳遞的 ,因此,如果在方法內部重新分配數組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
}
}
您的錯誤在於數組初始化,在Java中,我們使用如下構造函數初始化數組:
int[] tab = new int[]{10,-2,12};
這是適合您的情況的正確代碼:
class Get{ static void fIntarray(int[] b){ b = new int[]{10};}}
希望它會有所幫助,祝您好運。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.