从我的程序中获得意外的输出

时间:2016-03-04 16:25:12

标签: java methods jgrasp

我目前正在制作拖拉机租赁计划,到目前为止,我有一个测试拖拉机和拖拉机类的主要方法。首先,我将发布拖拉机课程,而不是发布主要方法:

拖拉机类:

class Tractor
{
   private int RentalRate;
   private int RentalDays;
   private int VehicleID;
   private int RentalProfit;

    public void setRentalRate(int r)
    {
      if (r > 0) {
            this.RentalDays = r;
        } else {
            System.out.println("Error: bad RentalRate!");
        }
         RentalDays = r;  
    } 

    public int getRentalRate() 
    {
      return this.RentalRate;
    }  

   public void setVehicleID(int v)
    {
      if (v > 0) {
            this.VehicleID = v;
        } else {
            System.out.println("Error: bad VehicleID!");
        }
         RentalDays = v;      
    }

    public int getVehicleID()
    {
      return this.VehicleID;  
    }

    public void setRentalDays(int d)
    {
      if (d > 0) {
            this.RentalDays = d;
        } else {
            System.out.println("Error: bad Rental Days!");
       }
         RentalDays = d;    
   }

    public int getRentalDays()
    {
      return this.RentalDays;
   }

    public int RentalProfit(int RentalRate, int RentalDays)  
    {
      RentalProfit = RentalRate * RentalDays;
      return this.RentalProfit;
    }   

    //Tractor(int RD, int RR, int RP, int VID)
    //{
      //RentalDays = RD;
      //RentalRate = RR;
      //RentalProfit = RP;
      //VehicleID = VID;

    //}


    @Override
    public String toString() {
        return  "Tractor (Rental days = " + RentalDays + ", Rental Rate = " + RentalRate + 
        ", Rental profit = " +  RentalProfit + ", VehicleID = " + VehicleID + ")";
    } 

主要方法:

public static void main(String[] args){
          Tractor tractor;
          tractor = new Tractor();
          tractor.setRentalRate(9);
          tractor.setRentalDays(45);
          tractor.setVehicleID(9145949);
          System.out.println(tractor.toString());

请参阅下面的程序给我的输出,我已多次查看我的代码并且无法弄清楚这是为什么。

Tractor (RentalDays = 9145949, Rental Rate = 0, Rental profit = 0, VehicleID 9145949)

2 个答案:

答案 0 :(得分:1)

您的setRentalRate方法不正确。在此方法中,您可以设置'RentalDays'而不是'RentalRate'。

public void setRentalRate(int r)
{
    if (r > 0) {
        this.RentalDays = r; // Should be this.RentalRate = r;
    } else {
        System.out.println("Error: bad RentalRate!");
    }
    RentalDays = r; // Should be RentalRate = r;
}

另外,我很困惑为什么你在if-else之后再设置一次。我认为它应该是这样的:

public void setRentalRate(int r)
{
    if (r > 0) {
        this.RentalRate = r;
    } else {
        System.out.println("Error: bad RentalRate!");
        RentalRate = 0;
    }
}

答案 1 :(得分:0)

我认为您提到的“怪异输出”是租车天数等于车辆ID?如果是,请参阅下文。

public void setVehicleID(int v)
{
  if (v > 0) {
        this.VehicleID = v;
    } else {
        System.out.println("Error: bad VehicleID!");
    }
     *****RentalDays = v;*****  <-- This is why.    
}
相关问题