简体   繁体   中英

How do I allow input of strings in JOptionPane

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM