Java - JOptionPane.InputDialog - 如果用户未输入任何内容并单击“确定”怎么办?
好吧,我正在尝试创建一种方法来检测用户是否未输入任何内容并单击“确定”。
例如,如果用户单击“取消”,我将使用以下代码中断 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当用户没有输入任何内容并点击“确定”时,您的程序仍然将字符串存储在您的单词数组中,该字符串恰好是空白的。检查字符串是否为空的一个简单方法是检查其长度,因此您想要的代码可能如下所示:
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: