首页 > 解决方案 > 以另一种方法返回更新值

问题描述

我有两种方法,在一种方法中更新变量的值,我想在第二种方法中调用更新后的值。

// Instance variables
private int numOfFirstClassSeats = 48;
...

在我的bookFirstClassSeats方法中,我从可用座位数中减去乘客人数。

numOfFirstClassSeats -= numOfFirstClassAdults;

我也有以下 getter 和 setter 方法。

public int getNumOfFirstClassSeats() {
    return numOfFirstClassSeats;
}

public void setNumOfFirstClassSeats(int numOfFirstClassSeats) {
    this.numOfFirstClassSeats = numOfFirstClassSeats;
}

所以在第一种方法中,我调用了getandset方法。

public void bookFirstClassSeats() {
    ...

    // Subtract the number of passengers from the number of seats available.
    numOfFirstClassSeats -= numOfFirstClassAdults;
    System.out.println("Available Seats: " + getNumOfFirstClassSeats());
}

打印正确的System.out.println()更新值 46。

在我的第二种方法中,我想显示可用座位数,如下所示。

public void printAvailableSeats() {
    System.out.println("First Class: " + getNumOfFirstClassSeats();
}

问题:当我运行这个功能时,我得到了相同的原始值,48。我明白为什么我没有得到更新的值,但我还没有弄清楚如何调用它。

编辑:澄清一下,这两种方法都在同一个类中。我有另一个名为 的类BookingSystem.java,我用它来运行该main方法并从另一个类调用上面的方法。

这是我的main方法代码:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String input;

    do {
        System.out.println("\n~ BOOKING SYSTEM ~");
        System.out.println("------------------");
        System.out.println("A. Book Seats");
        System.out.println("B. View Available Seats");
        System.out.println("X. Exit\n");

        System.out.print("Select an option: ");
        input = sc.nextLine();

        if (input.length() > 1)
            System.out.println("ERROR: You can only enter a single character!");
        else {
            input = input.toUpperCase();

            switch(input) {
                case "A":
                    new BookingReceipt().bookSeats();
                    break;

                case "B":
                    new BookingReceipt().printAvailableSeats();
                    break;

                case "X":
                    System.out.println("INFO: You have exited the booking system.");
                    break;

                default:
                    System.out.println("ERROR: Invalid input!");
            }
        }
    } while (input.equals("X") == false);

    sc.close();
}

标签: java

解决方案


well, you made that setter; call it!

For example:

public void bookFirstClassSeats() {
    ...

    // Subtract the number of passengers from the number of seats available.
    numOfFirstClassSeats -= numOfFirstClassAdults;
    setNumOfFirstClassSeats(numOfFirstClassSeats);
    System.out.println("Available Seats: " + getNumOfFirstClassSeats());
}

Note the object oriented mindset goes a little further than rote getters and setters. Whatever class has the numOfFIrstClassSeats field should probably have the book method, too.


推荐阅读