在while循环中比较char - 从未满足条件

时间:2014-10-16 18:19:21

标签: java while-loop char

所以我有一个非常恼人的问题,我希望你们中的一个可以帮我解决。这是一个非常简单的程序,用星号打印我的COMP科学用户名。我为用户附加了一个选项 - 要么用星号打印用户名,要么只打印字符。

我构建了一个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

3 个答案:

答案 0 :(得分:2)

while语句表达式始终为true,因为并非所有表达式都可以同时为true - 您需要条件&&运算符

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

答案 1 :(得分: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,因此无法完成。

答案 2 :(得分: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