2016-05-17 54 views
-1

我想要做的是給2至60之間的數字。如果數字不包括在這個「空間」,那麼將有一個例外,名稱InvalidLicenceNumberException。我有和類UserInput,但它並不需要上傳其確定 我的主:例外如何使用,如果在嘗試趕上

import java.io.*; 
public class Exercv { 
    public static void main(String[] args) { 
     int ArTh ; 
     ArTh=Vehicle.NumberPos(); 
     try { 
      if(ArTh<2 || ArTh>60){ 
       ArThEx(); 
      } 
     } catch(InvalidLicenceNumberException e){ 
      System.out.println(""+e); 
      throw new InvalidLicenceNumberException ("There is an exception!"); 
     } 
    }   

我的類車輛:

public abstract class Vehicle { 
static int user; //for userinput 
    public static int ArTh() { 
     System.out.println("Give number between 2 until 60"); 
     user=UserInput.getInteger(); 
     if(user>=2 && user<=60){ 
      System.out.println(" Possition is : "+ user); 
     } 
     return user; 
    } 

    public static void ArThEx() throws ArithmeticException{ 
     System.err.println("There is an exception"); 
     System.err.println("Positions arent acceptable"); 
    } 
    } 

我的特例:

import java.lang.Exception; 

public class InvalidLicenceNumberExceptio extends MyException { 
    public InvalidLicenceNumberExceptio(String s){ 
     super(s); 
    } 
} 
+0

請格式化您的代碼。 – SomeJavaGuy

+0

是的,我看到我沒有做得很好對不起。我會 –

+0

這可能是有聯繫的,並且很有用:[我如何創建一個異常,以遏制int範圍等...](http://stackoverflow.com/questions/15468418/how-can-i-create-an-exception-that-c​​hecks-for-int-range-number-type-and-not-a) –

回答

0

你可以直接把你的例外,是這樣的:

if (user < 2 || user > 60) { 
     throw new InvalidLicenceNumberException("Your number needs to be between 2 and 60"); 
     System.exit(1); 
    } 

或者在你的ArThEx功能,這是通常的封裝它這是一個更好的做法。

public static void ArThEx() throws InvalidLicenceNumberException { 
    throw new InvalidLicenceNumberException("Your number needs to be between 2 and 60 (you typed " + user + ")"); 
    System.exit(1); 
} 
+0

有兩種不同的選擇?如果是,在方法的第二選擇上,我會在主要上寫什麼? –

+0

確實有兩種不同的選擇。首先,我會直接將它放入「Vehicle」類。第二,是的,我會把它放在你的'main'函數中,直接檢查你的範圍。 –

0

你可能想要類似下面的代碼。

請注意,從主方法重新拋出異常是沒有意義的,因爲無論如何什麼都不會收到。 所以只打印您的消息,讓程序結束(可能迫使與System.exit退出代碼)

public static void ArThEx() throws InvalidLicenceNumberException{ 

    System.err.println("There is an exception"); 
    System.err.println("Positions arent acceptable"); 
    throw new InvalidLicenceNumberException("Out of range"); 
} 
+0

如果我明白要刪除我在類上創建的方法車輛ArThEx?也可以取代你在我的主要上寫的東西嗎? –

+0

如果此方法的目的僅僅是打印事件並拋出異常,它不必位於'Vehicle'類中。這可能是你的主要課程的一種方法。 – Berger

0

試圖改變自己的ArThEx方法,這樣,讓我知道,如果它

public static void ArThEx() throws ArithmeticException{ 
     System.err.println("There is an exception"); 
     System.err.println("Positions arent acceptable"); 
     throw new InvalidLicenceNumberExceptio(); 
    }