首页 > 解决方案 > 用户在字符串中输入值后退出 While 循环 (Java)

问题描述

你好 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;
}

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

标签: javastringvalidationinputwhile-loop

解决方案


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

推荐阅读