Freedom
Freedom

Reputation: 347

Java - GUI's in Netbeans - I have a error

I'm trying to make a calculator, and part of it is to implement a thing where if it reads the from the first text area as a number x, then the second text area as 0, it will send out a error message. The following doesn't seem to work though...

private void 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);
}                                            

It just doesn't seem to display the error I wanted. Could someone help?

---------EDIT----------

Woops sorry guys I just noticed that it said this.firstInput instead of this.secondInput. I totally facepalmed sorry....

Thanks man!

Upvotes: 0

Views: 307

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347204

Apart from the fact that you were trying to check the value from the first field and not the second, the structure of your code would still allow the execution of the calculation, instead, you should be using a if-else statement, for example.

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);            
}

}

Also, you've already done the conversion of the Strings, you might as well use the results you already have - or try and do String comparison instead if you want to avoid the conversations altogether...

Upvotes: 1

Related Questions