2014-02-09 99 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块来捕获异常并打印消息。 –

相关问题