0

If I want to allow input of an integer in JOptionPane, I would need

String something= JOptionPane.showInputDialog(null, " ");
int x = Integer.parseInt(something);

However, this time I want to input string into the JOptionPane InputDialog. Is there any way similar to int x = Integer.parseInt(); but works for the string?

And, how do I make an advance feature whereby the program will be able to detect error such as invalid input? Eg. when the user(s) input space and enter instead of a value or a word, or their answer is out of range. So basically their answer is something like space or -99 when answer should be within 1 to 100.

I'm sorry if this sounds dumb, I am very new to programming.

Blue
  • 545
  • 3
  • 13
Tragend
  • 17
  • 1
  • 3
  • 1
    You already get a ```String``` from the input dialog, why would you want to parse it into a ```String``` again? – Jorn Vernee May 18 '16 at 12:16

2 Answers2

1
 public static void main(String[] args) {
        String message = JOptionPane.showInputDialog(null, "Enter a message:");
        boolean validMessage = false;
        do {
            if (isMessageEmpty(message)) {
                message = JOptionPane.showInputDialog(null, "No message entered! Enter a message:");
            } else {
                if (Integer.parseInt(message) > 100 || Integer.parseInt(message) < 0) {
                    message = JOptionPane.showInputDialog(null, "Message not acceptable, please enter a valid message::");
                } else {
                    validMessage = true;
                }
            }
        } while (!validMessage);
    }

    private static boolean isMessageEmpty(String message) {
        return message.trim().isEmpty();
    }
Daniel Almeida
  • 372
  • 1
  • 14
0

Is there any way similar to Int x = Integer.parseInt(); but works for the string?

To answer your first question, there is a way. Like @John Verner said, just use the string you get from JOptionPane! No need to do anything special to it.

And, how do I make an advance feature whereby the program will be able to detect error such as invalid input?

Try using Integer.parseInt(); on the string you get. If it throws and exception or the returned int isn't in the specified range, tell the user to input again.

For more information on catching exceptions, click here.

Blue
  • 545
  • 3
  • 13