[英]Java: Using a mutator method on element of array with a for loop, not working
這項任務要求我們為具有各種房間對象的“酒店”創建一個數組,這些房間將具有房間號和價格元素。
我試圖通過生成此2D數組開始,然后使用for循環,該循環使用mutator方法設置該數組的每個“房間號”。 代碼可以編譯,但是我得到一個nullpointerexception錯誤。
我認為,一旦我了解了為什么我的方法不能在元素上起作用,我就可以了。 其余的只是掃描程序輸入和一些異常處理(無效的輸入,我只能使用throws ioexception東西,對吧?)
謝謝!
這是代碼:
public class Hotel{
public static void main(String[] args){
int choice = 0;
System.out.println("Welcome to the Hotel California.");
Scanner sc = new Scanner(System.in);
Room[][] hotel = new Room[8][20];
for(int i = 0; i< hotel.length; i++){
for(int j = 0; j<hotel[i].length;j++){
int roomNum = (i * 100) + j + 1;
hotel[i][j].setRoom(roomNum);
}
}
System.out.println(hotel[0][0].getRoomNumber());
do{
System.out.println("What business have you today?");
System.out.println("1. Guest Registration");
System.out.println("2. Guest Checkout");
System.out.println("3. Show me occupied rooms");
System.out.println("4. Exit");
choice = sc.nextInt();
}while(choice != 4);
}
}
默認情況下, Object
數組中的元素為null
。 在嘗試調用數組上的任何方法之前,初始化數組本身內的元素
for (int i = 0; i < hotel.length; i++) {
for (int j = 0; j < hotel[i].length; j++) {
hotel[i][j] = new Room();
...
}
}
public class Hotel{
public static void main(String[] args){
int choice = 0;
System.out.println("Welcome to the Hotel California.");
Scanner sc = new Scanner(System.in);
Room[][] hotel = new Room[8][20];
for(int i = 0; i< hotel.length; i++){
for(int j = 0; j<hotel[i].length;j++){
int roomNum = (i * 100) + j + 1;
//hotel[i][j] is not initialized yet
hotel[i][j] = new Room();
//hotel[i][j] is initialized
hotel[i][j].setRoom(roomNum);
}
}
System.out.println(hotel[0][0].getRoomNumber());
do{
System.out.println("What business have you today?");
System.out.println("1. Guest Registration");
System.out.println("2. Guest Checkout");
System.out.println("3. Show me occupied rooms");
System.out.println("4. Exit");
choice = sc.nextInt();
}while(choice != 4);
}
}
我已對您的代碼進行了更正。 如果Room
的構造函數需要參數,則將其添加到構造函數調用中。 hotel[i][j]
未初始化,因此您無法引用hotel[i][j].
的setRoom
方法hotel[i][j].
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.