2014-02-09 104 views
-1

我有下面的代碼 - 在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); 

} 
} 
+0

你是如何輸入參數無效? –

+0

在驅動程序類中,我使用負值的實例。 E.G:-32,-9,-11等。 –

+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"); 
    } 
} 
+0

這確實有效並解決了我的問題,謝謝大家。我問這是因爲我自己學習這個@ home,但它可能不是說「java.lang ...」它只是顯示消息「Values must be positive」?或者我應該使用try和catch塊嗎? –

+0

有不同的方式來處理它,但可能現在最簡單的方法是在VehicleTest中引入try/catch塊來捕獲異常並打印消息。 –

相關問題