0

私は電卓を作ろうとしていますが、その一部は、最初のテキスト領域から数値 x を読み取り、2 番目のテキスト領域を 0 として読み取ると、エラーメッセージを送信することを実装することです。以下はうまくいかないようですが...

プライベートボイドdivideButtonActionPerformed(java.awt.event.ActionEvent evt) {

    int number1, number2;
    int y = Integer.parseInt(this.firstInput.getText());
    if (y == 0) {
        JOptionPane.showMessageDialog(this, "Cannot divide by 0", "Error", JOptionPane.ERROR_MESSAGE);
    }
    try {
        number1 = Integer.parseInt(
                this.firstInput.getText());


    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Bad first number", "Error", JOptionPane.ERROR_MESSAGE);
        return;
    }
    try {
        number2 = Integer.parseInt(
                this.secondInput.getText());
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Bad second number", "Error", JOptionPane.ERROR_MESSAGE);
        return;
    }

    int answer = number1 / number2;
    this.theAnswer.setText(
            "The calculated answer is: " + answer);
}                                            

私が望んでいたエラーが表示されないようです。誰か助けてくれませんか?

- - - - -編集 - - - - -

申し訳ありませんが、this.secondInput ではなく this.firstInput と表示されていることに気付きました。私は完全に顔をしかめました。

ありがとう!

4

1 に答える 1

1

2 番目のフィールドではなく最初のフィールドの値をチェックしようとしていたという事実は別として、コードの構造では計算を実行できますが、代わりにif-elseステートメントを使用する必要があります。

int number1, number2;
try {
    number1 = Integer.parseInt(
            this.firstInput.getText());


} catch (Exception e) {
    JOptionPane.showMessageDialog(this, "Bad first number", "Error", JOptionPane.ERROR_MESSAGE);
    return;
}
try {
    number2 = Integer.parseInt(
            this.secondInput.getText());
} catch (Exception e) {
    JOptionPane.showMessageDialog(this, "Bad second number", "Error", JOptionPane.ERROR_MESSAGE);
    return;
}
if (number2 == 0) {
    JOptionPane.showMessageDialog(this, "Cannot divide by 0", "Error", JOptionPane.ERROR_MESSAGE);
} else {
    int answer = number1 / number2;
    this.theAnswer.setText(
            "The calculated answer is: " + answer);            
}

}

また、すでに s の変換を行っているので、String既にある結果を使用することもできます。またはString、会話を完全に避けたい場合は、代わりに比較を試みてください...

于 2013-10-16T00:18:21.890 に答える