I noticed a few things about my results from my codes.

If I don't key in anything,no matter what I press(the ok,cancel or the x button)
It will print out

Please enter an integer
value cannot be 0 or negative

and contiune to prompt me until the I key in a positive
value

If I type in a string value, it will also print out

Please enter an integer 
value cannot be 0 or negative

and contiune to prompt me until the I key in a positive
value

what I want is

when I click on ok button

it will check whether the value is <=0 or is a string value.

if the value is a string value, it will print out

  Please enter an integer   

if the value is <=0, It prints out

  value cannot be 0 or negative

when I click on cancel or the x button, it will close the JOptionPane

Please help.thanks

import javax.swing.JOptionPane;

public class OptionPaneTut {
    public static void main(final String[] args) {
        int value = 0;
        boolean isPositive = false;
        do {
            try {
                value = Integer.parseInt(JOptionPane.showInputDialog(null,
                        "Enter value?", null));
            } catch (NumberFormatException e) {
                System.out.println("Please enter an integer");
            }

            if(value <= 0) {
                System.out.println("value cannot be 0 or negative");
            }

            else {
                System.out.println("value is positive");
                isPositive = true;

            }
        }while(!isPositive);
    }
}

Recommended Answers

All 4 Replies

There are lots of ways to do this, here's one that is easy to read...
have an isNumeric boolean. Start with it true, then set it false in the catch clause if you get a NumberFormatException. Put the messages (lines 15 - 23) inside an if (isNumeric) ...

thank you.
There is one more problem I am facing
if I don't key in anything,no matter what I press(the ok,cancel or the x button), it will prompt me until the I key in a positive
value. but I only want the prompt to happen when i pressed ok.

If I click on cancel or the x button, it will close the JOptionPane

If you do anything except press OK then the dialog returns a null instead of a String. So you need to assign the returned value to a String and test that for == null. If it's not null then you can go on to try parsing it as an int etc.

  1. Please enter an integer
  2. value cannot be 0 or negative

put there JFormattedTextField, better JSpinner with number formatter, more in Oracle tutorial

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.