【问题标题】:Input Validation Loop输入验证循环
【发布时间】:2016-03-07 01:18:12
【问题描述】:

所以我的程序允许用户输入一个字符串,然后删除所有出现的字符。如果字符串中不存在该字符,则应打印一条错误消息。现在,我创建了一个循环来检查字符串中的每个字符,以创建没有字符的新字符串。我不确定如何创建输入验证循环,而不为每个与用户要删除的字符不匹配的字符打印错误消息。我希望这是有道理的!

这是我的代码的一部分:

//REMOVE LOOP
System.out.println("Enter the character to remove");
String oldChar = keyboard.nextLine();

while ( indexEnd <= string.length() ) {
    String substring = string.substring(indexStart, indexEnd);
    indexStart++;
    indexEnd++;

}

    while ( substring.equals(oldChar) ) {
         substring = string.substring(0, indexStart-1);
         string = substring + string.substring(indexEnd - 1);
         indexStart=0;
         indexend=1;
    }
}

【问题讨论】:

  • 我建议只使用其中一种字符串方法 (str.replace(c, ""))。也就是说,除非这是一项家庭作业,您必须使用循环来完成。
  • 请添加堆栈跟踪和代码。你也可以看看How to Ask 来改进这个问题。欢迎来到 SO!

标签: java validation input


【解决方案1】:

在开头添加一个保护子句(检查)。

最好避免while循环,写一些更易读的东西。

public String removeCharacter(String text, String character) {
    if(!text.contains(character)) {
        throw new IllegalArgumentException("Character " + character + " not found in text " + text);
    } else {
        return text.replace(character, "");
    }
}

【讨论】:

    【解决方案2】:

    虽然 Swifter 的答案很棒且更具可读性,但这里有另一种选择:

    由于我们只是删除字符,我们知道如果结果长度保持不变,则找不到该字符。

    public String remove(String text, String character) {
        // save the original length because we are going to use it later
        var origLength = text.length();
    
        text = text.replace(character, "");
    
        // check new length against original length
        // - if they are the same, then 'character' wasn't found
    
        if(origLength == text.length()) {
            throw new IllegalArgumentException("Character " + character + " not found.");
        }
    
        return text;
    }
    

    从技术上讲,这更高效,因为只有一次通过字符串(尽管实际上可以忽略不计)。

    【讨论】:

      猜你喜欢
      • 2021-05-13
      • 2014-10-11
      • 1970-01-01
      • 2016-05-27
      • 2012-11-10
      • 2015-05-19
      • 2019-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多