我是一個嘗試使用不同文件中定義的類的新手Java程序員。所以,我寫了這兩個.java文件:如何從另一個類中定義的類創建數組
首先,有MyLibrary.java:
package mymainprogram;
public class MyLibrary {
public class MyRecord {
int number;
char letter;
}
public static int TriplePlusThree(int input_number) {
return ((input_number*3) + 3);
}
}
然後,MyMainProgram.java:
package mymainprogram;
import java.util.Scanner;
public class MyMainProgram {
public static void main(String[] args) {
Scanner keyread = new Scanner(System.in);
System.out.print("Enter Number to Process: ");
int num = keyread.nextInt();
int result = MyLibrary.TriplePlusThree(num);
System.out.println("3x + 3 = "+result);
String letters = "ABCDEFGHIJ";
MyLibrary.MyRecord[] TenRecs = new MyLibrary.MyRecord[10];
for (int i = 0; i < 10; i++) {
TenRecs[i].number = i; //NullPointerException here
TenRecs[i].letter = letters.charAt(i);
}
}
}
我沒有使方法工作得很好的問題;現在我的目標是創建一個數組,其中每個成員都有一個整數和字符。 (注意:我不是在尋找更好的方法來實現這個目標,我只是用這個簡單的例子來試圖實現這個目標)。
當我試圖運行我的程序,我得到:
java.lang.NullPointerException
我研究這個,發現this page,它說:
If we try to access the objects even before creating them, run time errors would occur. For instance, the following statement throws a NullPointerException during runtime which indicates that [this array] isn't yet pointing to [an] object. The objects have to be instantiated using the constructor of the class and their references should be assigned to the array elements in the following way.
studentArray[0] = new Student();
所以,我想這樣做在我的主程序中:
MyRecordArray[0] = new MyLibrary.MyRecord();
但它給出了這個錯誤:
an enclosing instance that contains MyLibrary.MyRecord is required
該錯誤信息導致我this Stack Exchange question,它說:
you have to create an object of X class (outer class) and then use objX.new InnerClass() syntax to create an object of Y class.
X x = new X();
X.Y y = x.new Y();
所以,按照這個答案,我添加這兩行我的程序:
MyLibrary mylibrary = new MyLibrary();
MyLibrary.MyRecord myrecord = mylibrary.new MyRecord();
這些行不會給出任何警告或編譯錯誤,所以我覺得我離得更近了一步,但我仍然在試圖弄清楚如何創建一個數組。我知道,如果我想讓整數數組,我只想做到這一點:
int[] TenInts = new int[10];
所以,我已經試過了諸如:
myrecord[] TenRecs = new myrecord[10];
MyRecord[] TenRecs = new MyRecord[10];
但沒有什麼工作,我覺得自己像我現在正在抓秸稈。我感覺到正確的眼睛可以很快解決這個問題。
我承認,這是一個有趣的語法。我只是試圖按照其他答案的語法,這個答案已經獲得了50個讚揚。 –