2016-03-07 112 views
-1

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

这里是我的代码的一部分:

//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; 
    } 
} 
+0

我会建议使用其中一种字符串方法(str.replace(c,“”))。也就是说,除非这是一项家庭作业,你必须在循环中完成作业。 –

+1

请添加堆栈跟踪和代码。您也可以查看[如何提问](http://stackoverflow.com/help/how-to-ask)来改进问题。欢迎来到SO! –

回答

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, ""); 
    } 
} 
0

虽然更快的答案是伟大的,更具可读性,这里是另一种选择:

因为我们只是删除字符,我们知道,如果得到的长度保持不变的字符没有被发现。

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

从技术上讲,这是更高性能,因为只有一个通过字符串(虽然实际上这是微不足道的)。