【问题标题】:Exiting While Loop After User Enters Value in String (Java)用户在字符串中输入值后退出 While 循环 (Java)
【发布时间】:2019-04-20 07:42:03
【问题描述】:

你好 StackOverflowers 朋友,我希望你一切顺利。

我对 Java 编程还比较陌生,并且发现自己陷入了困境。

我正在尝试做的是;

  1. Java 中的输入验证 - 我想确保 JOptionPane.showInput 窗格继续重新出现(使用 while 循环),直到用户输入了一个在“this.accountName”字符串中捕获的值,并且;
  2. 一旦用户在 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;
}

解决此问题的最佳方法是什么? 提前感谢您的帮助!

【问题讨论】:

  • 可能想重新考虑这门课。 getter 不应该改变实例的状态。
  • 这个 'if (this.accountName.contains(""))' 将始终返回 true,除非 accountName 为 null,在这种情况下它会抛出 NullPointerException。
  • 您可能应该检查对话框结果是空的还是只是空白。试试this.accountName!= null && this.accountName.trim().length() != 0

标签: java string validation input while-loop


【解决方案1】:

使用 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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 2019-03-19
    • 2020-08-08
    • 1970-01-01
    • 2014-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多