我有下面的代碼 - 在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等。 –
你確定它編譯正確嗎?在此代碼塊中的任何位置都有語法錯誤。 –