Java如果用户输入的数量超出范围选择=用户定义的异常JOptionPane

时间:2017-10-12 02:55:53

标签: java

我一直在努力解决这个问题。我想使用JOptionPane进行输入,如果用户输入大于4的数字。它将获得我所做的InvalidChoiceException。请原谅我,如果这可能是重复但我似乎无法找到答案。希望有人可以提供帮助。

测试类

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 Class

//TEST PROJECT
public class InvalidChoiceException extends Exception {

    private double choice;

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

ExceptionTest Class

//TEST PROJECT
public class ExceptionTest 
{

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


    }
}

1 个答案:

答案 0 :(得分: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!");
        }


    }
}

作为上面评论中提到的Hovercraft Full Of Eels,自定义异常应该调用super(String message)。这样您就可以将消息传递给超类(Exception),然后通过调用e.getMessage()来在catch块中检索它;