在while循环中比较字符--条件永远不会满足



所以我有一个非常烦人的问题,我希望你们中的一个人能帮我解决。这是一个非常简单的程序,可以用星号打印我的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("4n");
        System.out.println("Jn");
        System.out.println("An");
    }//end of else
}//end of main

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

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

您的逻辑or应该是逻辑的,并且这个

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

应该是

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

while循环的问题是没有符合条件的字符。考虑小写的l,当usersChoice是l时,它不是L,所以它不会完成。

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

相关内容

最新更新