2014-09-24 72 views
0

我正在做一個Java程序,需要涉及一些錯誤檢查。進入一個無效的字符串雖然不(或相當)java

while (n == 0){ 
    System.out.println("Can't use 0 as a denominator! Please enter a real, nonzero number"); 
    n = input.nextInt(); 
} 

但我怎麼阻止用戶:我可以進入壞數值輸入像這樣(假設input掃描儀已經創建)阻止用戶?我不能使用!=,因爲字符串只能與string.equals()方法比較,對吧?那麼,有沒有一段時間沒有循環?即:

while !(string.equals("y") || string.equals("n")){ 
    //here have code 
} 

或者這種性質的東西?

回答

5

雖然是作爲同時,不循環中沒有這樣的事情,你總是可以反轉條件:

while (!(string.equals("y") || string.equals("n"))){ 

這被讀取,「而字符串不等於」y「或」n「」。

您也可以應用德摩根的身份爲改寫這個:

while (!(string.equals("y")) && !(string.equals("n"))){ 

這是一個有點清晰「雖然字符串不等於‘Y’,不等於‘n’」 。

2

你幾乎得到它,只是改變在那裏你定位你的! 這樣的:

while (!(string.equals("y") || string.equals("n"))) 
3

沒有while-not指令,但您可以簡單地否定正常的while循環中的條件。試試這個:

while (!string.equals("y") && !string.equals("n")) 

甚至更​​好,謹防其中的字符串是null的情況下和/或它在不同的情況下:

while (!"y".equalsIgnoreCase(string) && !"n".equalsIgnoreCase(string)) 
1

爲什麼不嘗試正則表達式?

Scanner sc = new Scanner(System.in); 
String string = sc.nextLine(); 
while (!string.matches("(?i)^(?:y|n|yes|no)$")) 
{ 
    System.out.println("Invalid input..."); 
    string = sc.nextLine(); 
} 
boolean answer = string.matches("(?i)^(?:y|yes)$");