简体   繁体   English

我如何在JOptionPane中输入字符串

[英]How do I allow input of strings in JOptionPane

If I want to allow input of an integer in JOptionPane, I would need 如果我想允许在JOptionPane中输入整数,则需要

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

However, this time I want to input string into the JOptionPane InputDialog. 但是,这次我想将字符串输入到JOptionPane InputDialog中。 Is there any way similar to int x = Integer.parseInt(); 有什么类似于int x = Integer.parseInt();方法吗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. 因此,当答案应在1到100之间时,基本上他们的答案是空格或-99。

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(); 有什么类似于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 ! 就像@John Verner所说的那样,只需使用从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(); 尝试使用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. 如果抛出异常,或者返回的int不在指定范围内,请告诉用户再次输入。

For more information on catching exceptions, click here. 有关捕获异常的更多信息, 请单击此处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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