如何在整个类中使用对象引用

时间:2014-03-24 23:02:37

标签: java reference

所以例如在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"
               }
            }

1 个答案:

答案 0 :(得分:3)

您在案例陈述中声明的变量是该陈述的本地变量,因此,在右侧,它们不会在它之外被看到。只需在switch()之前(上方)声明您的变量,它就会对所有变量都可见。

编辑:这个例子是对Brian Roach的回应:

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;
    }     
}

编译器抱怨:" bar无法解析为变量"

要修复,请将bar的声明移动到与foo声明相同的位置。