值在方法中不断重置

时间:2021-03-24 18:48:32

标签: java methods

这应该是一个非常简单的问题,但由于我对编程很陌生,我似乎无法弄清楚。 我想计算餐厅的可用座位数,并在每次新预订(下订单)后减去免费座位数。

我已将 'restaurantCapacity' 的起始值设置为 10,但它在每个新组之后重置回 10。我如何覆盖这个值。 问题应该出在方法'seatCapacity'

如果代码运行正常,它应该还有 1 个座位。 (10 - 4 组 - 5 组 = 1)

public class Reservation {
  int guestCount;
  int restaurantCapacity =10;
  boolean isRestaurantOpen;
  boolean isConfirmed;

//Constructor
  public Reservation(int groupSize, boolean restaurantStatus){
    guestCount = groupSize;
    isRestaurantOpen = restaurantStatus;
    //Order not filled
    if (isRestaurantOpen == false || guestCount > restaurantCapacity){
      System.out.println("Sorry, we were not able to fill your order.");
      //Reason
      if(isRestaurantOpen == false){
        System.out.println("We are currently closed.");
      }
      else{
        System.out.println("We are out of seats.\n");
      }
      isConfirmed = false;
    }
    //Succesfull Order
    else{
      System.out.println("Your order has been filled");
      isConfirmed = true;
    }
  }

//Number of free seats------------------------------------
//METHOD WITH THE PROBLEM!

  public void seatCapacity(boolean isConfirmed){
    if (isConfirmed == true){
      System.out.println(restaurantCapacity); //----VALUE STAYS AT 10??
      restaurantCapacity -= guestCount;
      System.out.println(guestCount + " seats have been taken. " + restaurantCapacity + " seats are remaining.\n");
      }
    }

//Main
  public static void main(String[] args){
    Reservation mason = new Reservation(4, true);
    mason.seatCapacity(true);
    Reservation johnson = new Reservation(5, true);
    johnson.seatCapacity(true);
  }
}

我尝试了很多东西,但每次都会重置。 我不知道是否有人会看到这个,但非常感谢帮助。 谢谢

3 个答案:

答案 0 :(得分:2)

简短的回答是让 restaurantCapacity static,这样它就会在 Reservation 的实例之间共享。

不过,我建议您考虑为餐厅本身建模一个对象。预订现在做的有点太多了,餐厅可以负责自己的容量并确定是否接受预订。

答案 1 :(得分:0)

你看,restaurantCapacity 是类 Reservation 的一个属性,这意味着每个实例都有自己的变量 restaurantCapacity。因此,当您创建 masonjohnson 时,每个都有自己的变量,具有单独的值 10(分别减去 4 和 5)。

如果您希望变量在同一类的实例之间共享,则必须将其声明为静态。尝试在要共享的属性声明之前添加 static

static int restaurantCapacity = 10;

答案 2 :(得分:0)

如果你想让一个变量保持他的旧值,让它静态会帮助你。

static int restaurantCapacity = 10;

对你来说已经足够了。

相关问题