2014-10-16 67 views
2

所以我有一個非常討厭的問題,我希望你們中的一個能幫我解決。這是一個非常簡單的程序,它將我的COMP科學用戶名以星號標記。我附加了一個用戶選擇 - 以星號打印用戶名或打印字符。在一個while循環中比較字符--- condtion永遠不會滿足

我構建了一個while循環,驗證用戶輸入的數據是否準確。這個while循環的條件永遠不會滿足 - 所以無論輸入什麼,它總是循環遍歷它。我確信這是一個非常簡單的問題,以前沒有真正使用過字符,所以無法弄清楚我做錯了什麼。

//===================================================== START OF MAIN 
public static void main (String [] args){ 
    Scanner input = new Scanner(System.in); // Scanner for users input 
    char usersChoice = 0;     // Variable for users input 

    System.out.println("\nWould you like to see the large letters or the small letters?\n (Enter L for large, S for small!!)\n"); 
    usersChoice = input.next().charAt(0); // Users Input 

    System.out.println(usersChoice); 

    //================================================= WHILE LOOP TO CHECK AUTHENTICITY OF DATA 
    while (usersChoice != 'l' || usersChoice != 'L' || usersChoice != 's' || usersChoice != 'S'){ 
     System.out.println("\nWrong Input - Please try again!!!\n"); 
     usersChoice = input.next().charAt(0); 
     System.out.println(usersChoice); 
    }//end of while 

    //================================================= IF (CHAR = L) PRINT BIG LETTERS 
    if (usersChoice == 'L' || usersChoice == 'l'){ 
     printU(); 
     print4(); 
     printJ(); 
     printA(); 
    }//end of if 

    //================================================= ELSE PRINT LETTERS 
    else{ 
     System.out.println("\nU"); 
     System.out.println("4\n"); 
     System.out.println("J\n"); 
     System.out.println("A\n"); 
    }//end of else 
}//end of main 

回答

2

while聲明表情總是true因爲不是所有的表達式可以一次是正確的 - 你所需要的條件&&操作

while (usersChoice != 'l' && usersChoice != 'L' && usersChoice != 's' && usersChoice != 'S') { 
+0

盲目提升此解決方案的人是誰? – user3437460 2014-10-16 18:27:45

+0

OP的while循環表達式總是爲TRUE而不是false。 – user3437460 2014-10-16 18:30:53

+0

謝謝,一切正常。實際上我對自己感到惱怒,因爲沒有更多地玩耍和解決問題。年輕的程序員嘿? – 2014-10-16 18:31:12

1

你的邏輯或(S)應該是合乎邏輯和(S),這

while (usersChoice != 'l' || usersChoice != 'L' || usersChoice != 's' || 
    usersChoice != 'S') 

應該

while (usersChoice != 'l' && usersChoice != 'L' && usersChoice != 's' && 
    usersChoice != 'S') 

while循環的問題是有沒有字符可以符合條件。考慮小寫l,當usersChoice是l它不是L所以它不會完成。

+0

非常感謝你 - 我知道我做了一些笨拙。已修復的問題 - 全部正在工作:) – 2014-10-16 18:30:05

0
while (!(usersChoice != 'l' || usersChoice != 'L' || usersChoice != 's' || usersChoice != 'S')) 

只要你while-loop前添加一個感嘆號。

while-loop總是不工作,因爲:

if userChoice is 'l', it is not 'L'/'s'/'S' (expression is true) 
if userChoice is 'L', it is not 'l'/'s'/'S' (expression is true) 
if userChoice is 's', it is not 'l'/'L'/'S' (expression is true) 
if userChoice is 'S', it is not 'l'/'L'/'s' (expression is true) 

while-loop始終計算爲true

+0

解決問題的有趣方法 - 謝謝 – 2014-10-16 18:30:35