Reputation: 23
so for example in a switch statement "case 1" I declare an Object reference variable, its all good, but if I try to use in a "case 2" it says that reference variable cannot be resolved.
How can I use it in every case?
Edit:
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"
}
}
Upvotes: 0
Views: 93
Reputation: 1541
Variables you declare inside your case statements are local to that statement, so, right-o, they won't be seen outside it. Just declare your variable before (above) the switch() and it'll be visible to them all.
Edit: this example is in response to Brian Roach below:
public void main(String[] args) { int foo = 11; switch (foo) { case 1: { int bar = 12; System.out.println("1"); break; } case 2: { System.out.println("2"); System.out.println("bar: " + bar); break; } default: { System.out.println("default"); break; } }
Compiler complains: "bar cannot be resolved to a variable"
To fix, move the declaration of bar to the same location as the declaration of foo.
Upvotes: 3