例如在switch語句「case 1」中我聲明瞭一個Object引用變量,它的全部都很好,但是如果我嘗試在「case 2」中使用它,引用變量無法解析。如何在整個類中使用對象引用
如何在任何情況下使用它?
編輯:
switch(choice){
case 1: {
if(HotelObj.getClassicRoomsAvailable() == 0 && HotelObj.getExecutiveRoomsAvailable() == 0){
System.out.println("Sorry, there are no available rooms");
break;
}else {
Scanner scanInput = new Scanner(System.in);
System.out.print("\nEnter desired room type: ");
System.out.print ("\nEnter \"Classic\" for a classic type room, price: 90$ for a day");
System.out.println("\nEnter \"Executive\" for a executive type room, price: 150$ for a day");
String roomChoice = scanInput.nextLine();
System.out.print("Enter your name: ");
String clientName = scanInput.nextLine();
System.out.print("Enter for how many days you'll stay:");
int stayingDays = scanInput.nextInt();
Client ClientObj = new Client(clientName, roomChoice, stayingDays);
Client.clientCount++;
if(roomChoice.equals("Classic")){
ClientObj.clientRoom = new Room("Classic");
ClientObj.setMoney(ClientObj.getMoney()- stayingDays * ClientObj.clientRoom.getPrice());
HotelObj.decClassicRooms(1);
HotelObj.addIncome(stayingDays*ClientObj.clientRoom.getPrice());
} else {
ClientObj.clientRoom = new Room("Executive");
ClientObj.setMoney(ClientObj.getMoney()-stayingDays * ClientObj.clientRoom.getPrice());
HotelObj.decExecutiveRooms(1);
HotelObj.addIncome(stayingDays*ClientObj.clientRoom.getPrice());
}
}
break;
}
case 2: {
System.out.println("Name: "+ClientObj.getName());
//Error "ClientObj cannot be resolved"
}
}
你可以發表你試過的一些代碼嗎? – ucsunil
由於'switch'語句的工作方式,所描述的在Java中顯然是錯誤的。任何在case中聲明的變量對所有後面的情況都是可見的,因爲case只是標籤,'switch'是封閉塊。請發佈一個你想要做什麼的例子,以及什麼不起作用。 –
後編輯:您的問題確實與開關無關。你已經在塊中聲明瞭一個變量('else'),這意味着它是唯一可以使用的地方。 –