2017-10-12 24 views
-1

我一直在爲此而苦惱。我想使用JOptionPane進行輸入,如果用戶輸入的數字大於4.它將得到我所做的InvalidChoiceException。請原諒我,如果這可能是重複的,但我似乎無法找到答案。希望有人能幫助。Java如果用戶輸入超出範圍選擇的數字=用戶定義的異常JOptionPane

測試類

import javax.swing.JOptionPane; 

public class RunThisSh { 

    public static void main (String [] args){ 

     ExceptionTest c = new ExceptionTest(); 

     try { 
      c.process(5); //I want to make this an INPUT in JOptionPane where if the user Enters a number greater than 4 
          // It will display an error 
     //JOptionPane.showInputDialog("Enter a Number: "); 
     } catch (InvalidChoiceException e) { 
      JOptionPane.showMessageDialog(null,"ERROR!"); 
     } 
    } 
} 

這是其他類。

InvalidChoiceException類

//TEST PROJECT 
public class InvalidChoiceException extends Exception { 

    private double choice; 

    public InvalidChoiceException (double choice) 
    { 
     this.choice = choice; 
    } 
    public double getChoice() 
    { 
     return choice; 
    } 
} 

ExceptionTest類

//TEST PROJECT 
public class ExceptionTest 
{ 

    Object process; 
    public void process (double choice) throws InvalidChoiceException 
    { 
     if (choice > 4) 
     { 
      throw new InvalidChoiceException(choice); 
     } 


    } 
} 
+1

你的異常類不應該有一個選擇字段,應該調用super的構造函數,傳入一個字符串。你有事情回來了。請去關於例外的教程。 –

+0

爲什麼不拋出IllegalArgumentException,趕上它,然後做任何在catch塊,而不是創建一個自定義異常? – smitty1

+0

@ smitty1因爲我的教授如此告訴我。這是一個案例研究,他甚至沒有教。 – eLjA

回答

0

也許這就是你想要的。

import javax.swing.JOptionPane; 

public class RunThisSh { 

    public static void main (String [] args){ 

     ExceptionTest c = new ExceptionTest(); 

     try { 
      c.process(5); //I want to make this an INPUT in JOptionPane where if the user Enters a number greater than 4 
          // It will display an error 
     //JOptionPane.showInputDialog("Enter a Number: "); 
     } catch (InvalidChoiceException e) { 
      JOptionPane.showMessageDialog(null,e.getMessage()); 
     } 
    } 
} 

//TEST PROJECT 
class InvalidChoiceException extends Exception { 

    public InvalidChoiceException (String message) 
    { 
     super(message); 
    } 

} 

//TEST PROJECT 
class ExceptionTest 
{ 

    public void process (double choice) throws InvalidChoiceException 
    { 
     if (choice > 4) 
     { 
      throw new InvalidChoiceException("Invalid Choice Entered!"); 
     } 


    } 
} 

作爲氣墊船Full Of Eels在上面的評論中提到,自定義異常應該有一個對super(String message)的調用。通過這種方式,您可以將消息傳遞給超類(Exception),然後通過調用e.getMessage()在catch塊中檢索它。

+0

但是我可以在哪裏輸入數字? – eLjA

+0

有幾種方法可以捕獲用戶輸入。例如,您可以使用Java Swing或AWT API創建表單,也可以使用掃描程序在命令窗口中捕獲用戶輸入,但此問題與使用自定義異常有關。我會建議搞清楚你想如何捕獲用戶輸入,然後找到一個關於如何去做的教程,因爲這將超出這個問題的範圍。 – smitty1