java - 用户在字符串中输入值后退出 While 循环 (Java)
问题描述
你好 StackOverflowers,我希望你所有的日子都过得很好。
我对 Java 编程还比较陌生,并且发现自己陷入了困境。
我正在尝试做的是;
- Java 中的输入验证 - 我想确保 JOptionPane.showInput 窗格继续重新出现(使用 while 循环),直到用户输入了一个在“this.accountName”字符串中捕获的值,并且;
- 从那里一旦用户在 JOptionPane.showInput 窗格中输入了一些内容,我想退出循环并继续我在我的 OO 程序中的其他方法。
不幸的是,我下面的 while 循环在第一个实例之后退出,并且在下面的代码示例中没有继续;
public String getAccountName() {
this.accountName = JOptionPane.showInputDialog(null, "Please enter a nick name for your new account (e.g. Savings Account)");
if (this.accountName!= null) {
while (this.accountName != null) {
this.accountName = JOptionPane.showInputDialog(null, "Error! Please enter a valid name for your new account");
if (this.accountName.contains("")){return this.accountName;
}
}
}
return this.accountName;
}
解决此问题的最佳方法是什么?我提前感谢您的帮助!
解决方案
使用 StringUtils.isBlank 方法 ( https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html ) 检查 accountName 值:
this.accountName = JOptionPane.showInputDialog(null, "Please enter a nick name for your new account (e.g. Savings Account)");
while (StringUtils.isBlank(this.accountName)) {
this.accountName = JOptionPane.showInputDialog(null, "Error! Please enter a valid name for your new account");
}
return this.accountName;
推荐阅读
- c# - 在没有拆分、不同和 foreach 的情况下查找字符串中最长的单词(并将其写出来)
- javascript - 需要帮助将缓冲区转换为节点中的字符串
- apache-spark - Windows 10 上的 pyspark 安装失败
- javascript - 如何使用 react.js 从 RESTAPI 获取数据
- c# - 如何在 AppCenter SDK for C# 中为 TrackError 注册事件处理程序?
- c# - 将表格元素加载到组合框中
- javascript - fs.opensync 不是函数
- codenameone - 代号一中的Android清单合并错误
- html - 将 Excel 文件内容显示为 HTML 表格 Angular
- c - GCC 中 strftime 的自定义语言环境字符串