2016-03-31 19 views
-3

Amacım, ayarlamamı traktöre atmaya değiştirmektir. Geçersiz değerler geçilirse, istisnaları yakalamak için ana yöntemimi değiştir. Sorun, bir istisna hatası yapmak için ayarlayıcılarımı nasıl değiştireceğimi bilmiyorum. Lütfen yardım et.Bir istisna hatası almak için bu kodu nasıl değiştiririm?

import java.util.*; 

public class tractorException 
{ 
     protected String name; 
     protected int VehicleID; 

    public String setName(String name) 
     { 
      return this.name = name; 

     } 

     String getName() 
     { 
      return this.name;   
     } 

    public int setVehicleID(int VehicleID) 
     { 
      if (VehicleID <= 0 || VehicleID > 100000) 
      { 
      return -1; 
      } 
      else 
      { 
       this.VehicleID = VehicleID; 
       return VehicleID; 

      } 
     } 

      public int getVehicleID() 
     { 
      return this.VehicleID; 
     } 

     tractorException() 
     { 
     setVehicleID(0); 
     setName(""); 
     } 

    @Override 
    public String toString() 
    { 
     return "Tractor Name= " + name + "VIN= " + VehicleID; 

    } 
    public static void main (String[] args) 
    { 

    } 
} 
+1

çok mantıklı değil Kodunuz - İlk kapalı, 'TractorException' Exception' veya' RuntimeException' 'bir alt sınıfı olmalıdır. İkincisi, muhtemelen bu kodun 'TractorException' içinde olmasını istemiyorsunuz. Bir öğreticiye (http://www.tutorialspoint.com/java/java_exceptions.htm) bakmak iyi bir başlangıç. – BadCash

cevap

1

yapıyor deneyin:

public class TractorException extends Exception 
{ 
    //implement whatever methods are necessary 
} 

bir Tractor temsil eden bir sınıfta. ana yöntemde

public int setVehicleID(int VehicleID) throws TractorException 
{ 
    if (VechicleID <= 0) { 
    throw new TractorException("Invalid VIN: " + VehicleID); 
    } 
    else { 
    this.VehicleID = VehicleID; 
    return this.VehicleID; 
    } 

} 

, yakalamak TractorException

+0

Teşekkür ederim biraz anlıyorum şimdi. – MajorJavaUser

İlgili konular