方法在那里,但它不像它应该的那样工作

时间:2014-02-09 00:26:06

标签: java

我有以下代码-in Java btw-并且它编译得很好但是当我输入无效参数时它不会将它们识别为错误并接受它们就好像它们符合条件。我关注的方法是SetMPG (int平均值)。这是我第一次来这里,所以如果我的问题含糊不清,我会道歉,如果有必要,我会填写更多信息。

public class Vehicle {
    // instance variables - replace the example below with your own
    private int tireCount;
    private int mPG;

    /**
     * Constructor for objects of class Vehicle
     */
    public Vehicle(int tCount, int mP) {
        // initialise instance variables
        tireCount = tCount;
        mPG = mP;
    }


    public void setTire(int tire) {
        if (tire >= 0) {
            tireCount = tire;

        } else/*if( tire < 0)*/ {
            throw new IllegalArgumentException("Values must be positive");
        }

    }

    public void setMPG(int average) {
        if (average > 0) {
            mPG = average;
        } else if (average < 0) {

            throw new IllegalArgumentException("Values must be positive");
        }

    }

    public int getTire() {
        return tireCount;
    }

    public int getMPG() {
        return mPG;
    }

    public String toString() {
        return String.format("There are " + tireCount + " tires and an average of " + mPG + "mpg");
    }

public class VehicleTest
{
// instance variables - replace the example below with your own
public static void main(String []args)
{
    Vehicle bike = new Vehicle( 2,-23); // first parameter is for tires , second is for   MPG
   System.out.println(bike);

}
}

1 个答案:

答案 0 :(得分:1)

根据您的代码和您所说的内容,您很可能是通过构造函数设置参数。将构造函数更改为以下形式:

public  Vehicle(int tCount , int mP)
{
    // initialise instance variables
    setTire(tCount);
    setMPG(mP);
}

也不确定0是否为mpg ???

的有效值
public  void  setMPG(int average)
{
     if( average > 0) //should it be >= 0???
     {
        mPG=average;
     }
     else if(average < 0) // should it be  <=0 ????
     {
        throw new IllegalArgumentException("Values must be positive");
     }
}