【问题标题】:How can I throw exception if user does not enter a binary value如果用户不输入二进制值,我该如何抛出异常
【发布时间】:2015-05-23 02:36:51
【问题描述】:

我想将用户的输入作为二进制值。如果他没有输入二进制(例如:3214),那么我想给出 WrongFormatException。但我无法管理尝试投掷的东西。这是我的控制器类。

我工作了一点,改成它。有什么有趣的部分我应该改变吗?它的工作顺便说一句。感谢您的帮助

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class Controller {

private View theView;
private Model theModel;

public Controller( View theView, Model theModel ){

    this.theView = theView;
    this.theModel = theModel;

    theView.addListener( new MyActionListener());   
}

public class MyActionListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent event) {

        int inputBinary = theView.getInputBinary();

        try {
            if ( checkFormat(inputBinary) )
            {
                int outputDecimal = theModel.convertToDecimal(Integer.toString(inputBinary));
                theView.setOutputDecimal(outputDecimal);
            }                   
            else
            {
                throw new WrongFormatException( "Wrong format");
            }

        } catch ( WrongFormatException e ) {

            theView.setOutputDecimal(0);
            theView.displayErrorMessage( "Wrong Format");
        }

    }
}

public boolean checkFormat ( int input )
{
    // check if it is not in true format
    String stringInput = Integer.toString(input);           
    for ( int i = 0; i < stringInput.length(); i++ )
    {
        if ( stringInput.charAt(i) == '0' || stringInput.charAt(i) == '1' )
        {

        }
        else
        {
            return false;
        }
    }
    return true;
}

// my own exception class
public class WrongFormatException extends Exception
{

    // CONSTRUCTOR

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

}   
}

这里是第一个代码,但忽略这部分。

 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;


public class Controller {

private View theView;
private Model theModel;

public Controller( View theView, Model theModel ){

    this.theView = theView;
    this.theModel = theModel;

    theView.addListener( new MyActionListener());   
}

public class MyActionListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent event) {

        // we got the input
        int inputBinary = theView.getInputBinary();

        // create an exception
        WrongFormatException problem = new WrongFormatException( "Input value is not binary");

        // base value, we assme the input is in true format
        boolean isTrueFormat = true;

        // check if it is not in true format
        String stringBinary = Integer.toString(inputBinary);            
        for ( int i = 0; i < stringBinary.length(); i++ )
        {
            if ( stringBinary.charAt(i) == '0' || stringBinary.charAt(i) == '1' )
            {

            }
            else
            {
                isTrueFormat = false;
                i = stringBinary.length();
            }
        }

        // we do the convertion work here
        int outputDecimal = theModel.convertToDecimal(Integer.toString(inputBinary));

        // and we set output textfield
        theView.setOutputDecimal(outputDecimal);


    }
}

// my own exception class
public class WrongFormatException extends Exception
{

    // CONSTRUCTOR

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

}   
}

【问题讨论】:

  • 旁注:在 Java 中,异常的堆栈信息在构造时存储,而不是在抛出时存储(如在 .NET 中)。因此,请考虑在更接近引发异常的位置调用new WrongFormatException。在大多数情况下,异常代码如下所示:throw new ...。
  • 如果您立即抓住它(在MyActionListener#actionPerformed 中),抛出WrongFormatException 有什么意义?
  • 是的,我也对此提出质疑。但我只是想学习抛出异常:D

标签: java exception binary try-catch throw


【解决方案1】:

如果您扩展 java.lang.RuntimeException 而不是 java.lang.Exception,您可以从 else 块中抛出 WrongFormatException 而无需声明 throws 子句

【讨论】:

    【解决方案2】:

    您可以使用Integer.parseInt(String s, int radix) 来验证输入是否为二进制。如果输入的格式不正确,parseInt 将抛出 NumberFormatException 异常,从而很容易解析和检查是否有效。

    Scanner in = new Scanner(System.in);
    
    while (true) {
        System.out.println("Enter a binary value: ");
        String input = in.nextLine();
    
        int value = 0;
        try {
            value = Integer.parseInt(input, 2);
        } catch (NumberFormatException nfex) {
            throw new WrongFormatException("Input value is not binary");// incorrect format
        }
    
        System.out.println("You entered \"" + value + "\" in base 10");
    }
    

    有一点需要注意,parseInt 上的文档说:

    ... 除了第一个字符可以是 ASCII 减号“-”(“\u002D”)表示负值或 ASCII 加号“+”(“\u002B”)表示正值...

    所以你可能需要检查...

    编辑: 从 cmets 看到我没有抓住重点。您的新代码非常好。

    【讨论】:

    【解决方案3】:

    用户输入一个字符串,所以像这样简单地把它作为一个字符串来测试:

    if (!input.matches("[01]+"))
        // it's not a binary, so throw exception etc
    

    【讨论】:

    • 我摆脱了 checkFormat 方法。谢谢
    猜你喜欢
    • 2016-08-14
    • 2020-08-21
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多