예를 들어 switch 문 "case 1"에서 객체 참조 변수를 선언합니다.하지만 모든 것이 좋습니다.하지만 "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' 문이 작동하는 방식 때문에 자바에서 명백하게 거짓입니다. 'case'에서 선언 된 변수는 대소 문자가 레이블이고'switch'가 둘러싼 블록이기 때문에 이어지는 모든 경우에서 볼 수 있습니다. 당신이하려는 일의 예와 정확하게 작동하지 않는 예를 게시하십시오. –
사후 편집 : 문제는 실제로 스위치와 관련이 없습니다. 블록 ('else') 안에 변수를 선언 했으므로이 변수는 사용할 수있는 유일한 장소입니다. –