2016-03-07 116 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; 
} 

從技術上講,這是更高性能,因爲只有一個通過字符串(雖然實際上這是微不足道的)。