[英]Having trouble calling an array from one method to another in Java
我設置代碼的方式是我在一個方法中聲明我的數組,然后我想在另一個表格中將它打印出來。 但是我想在只使用main()函數的情況下這樣做。
我已經把大部分不相關的代碼拿出去了,所以這里是我的代碼:
public static void main(String[] array) {
test2(array);
}
public static void test() {
String[] array = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16"};
}
public static void test2( String[] array ) {
int count = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(array[count] + "\t");
count++;
}
System.out.println();
System.out.println();
System.out.println();
}
}
當我嘗試運行它時,它會在“System.out.print(array [count] +”\\ t“)行中找到java.lang.ArrayOutOfBound;”
有誰知道這是為什么和/或如何解決它?
你有幾個錯誤:
test()
中將array
創建為局部變量。 test()
。 結果是你可能沒有參數調用你的應用程序,並最終讓test2()
方法試圖訪問空數組的第一個元素,導致你的異常。
這是你應該做的,但繼續閱讀代碼后,我沒有完成:
public static void main(String[] args) { // This array is defined, but don't use it.
test2(test());
}
public static String[] test() {
return new String[]{"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16"};
}
public static void test2( String[] array ) {
int count = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(array[count] + "\t");
count++;
}
System.out.println();
System.out.println();
System.out.println();
}
}
此代碼仍有問題。 您確實假設您的數組中有16個元素。 但你不確定。 哦,是的,你確定,因為你已經添加了它們,但你不應該認為它總是如此。
因此,無論如何都要檢查元素的實際數量。
public static void test2( String[] array ) {
int count = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (count < array.length) {
System.out.print(array[count] + "\t");
count++;
}
}
System.out.println();
System.out.println();
System.out.println();
}
}
好吧,它不起作用,因為當你的“main”調用“test2(array)”時它什么都沒有傳遞,因為main沒有定義一個“數組”。
您想要的數組僅存在於“test”方法中。
因此,一個簡單的解決方案是將代碼更改為:
public static void main(String[] array) {
test2(test());
}
public static String[] test() {
String[] array = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16"};
return array;
}
public static void test2( String[] array ) {
int count = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(array[count] + "\t");
count++;
}
System.out.println();
System.out.println();
System.out.println();
}
}
...這樣方法test()在main中調用時返回數組。
但是,代碼仍然沒有多大意義,特別是在面向對象編程中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.