我有下面的代码 - 在Java btw-,它编译得很好,但是当我输入无效参数时,它不会将它们识别为错误并接受它们,就好像它们一样符合条件。有关我的方法是SetMPG(int average)。这是我第一次来这里,所以我很抱歉,如果我的问题是模糊的,我会填写更多的信息,如果有必要。该方法在那里,但它不工作,就像它应该
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);
}
}
你是如何输入参数无效? –
在驱动程序类中,我使用负值的实例。 E.G:-32,-9,-11等。 –
你确定它编译正确吗?在此代码块中的任何位置都有语法错误。 –