Java - JOptionPane.InputDialog - 如果用户未输入任何内容并单击“确定”怎么办?

发布于 2024-09-25 18:04:04 字数 694 浏览 0 评论 0原文

好吧,我正在尝试创建一种方法来检测用户是否未输入任何内容并单击“确定”。

例如,如果用户单击“取消”,我将使用以下代码中断 while 循环:

if (words[i] == null) break; //breaks out of while loop

我为用户单击“确定”尝试了以下操作:

else if (Character.isDigit(words[i].charAt(0)) && words[i].charAt(0) == JOptionPane.OK_OPTION) break;

如果用户单击“确定”但没有骰子,则中断循环。我收到此异常:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at Project1.main(Project1.java:21)

OK_OPTION 的类型为 int,这就是我转换为 int 的原因。有人对我如何做到这一点有任何想法吗?

我发现这篇关于“取消”按钮的文章,但没有找到关于“确定”按钮的内容。谢谢!

Well, I'm trying to create a way of detecting if the user inputs nothing and clicks 'OK.'

For example, if the user clicks cancel, I break out of a while loop with the following code:

if (words[i] == null) break; //breaks out of while loop

I tried something along these lines for a user clicking OK:

else if (Character.isDigit(words[i].charAt(0)) && words[i].charAt(0) == JOptionPane.OK_OPTION) break;

to break out of the loop if the user were to click OK, but no dice. I get this exception:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at Project1.main(Project1.java:21)

OK_OPTION is of type int which is why I converted to int. Does anybody have any ideas of how I can do this?

I found this post about the 'Cancel' button but nothing about the 'OK' button. Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

‖放下 2024-10-02 18:04:04

当用户没有输入任何内容并点击“确定”时,您的程序仍然将字符串存储在您的单词数组中,该字符串恰好是空白的。检查字符串是否为空的一个简单方法是检查其长度,因此您想要的代码可能如下所示:

// break if user enters blank input
if( words[i].length() == 0 ) break;

When a user enters no input and hits okay, your program is still storing the string in your words array, the string just happens to be blank. An easy way to check if the string is blank is by checking its length, so the code you want could look like:

// break if user enters blank input
if( words[i].length() == 0 ) break;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文