【问题标题】:using Or in if/else statement issue [duplicate]在 if/else 语句问题中使用 Or [重复]
【发布时间】:2022-10-01 01:32:30
【问题描述】:

java初学者。试图让我的代码只接受某个字母等级输入或以其他方式退出系统。当我输入这段代码时,

System.out.print(\"What letter grade do you want to achieve for the course? \");
char desiredGrade = keyboard.next().toUpperCase().charAt(0);
    
if (desiredGrade != \'A\') {
    System.out.println(\"Invalid input\");
    System.exit(0);
}

它工作正常,并读取除 \'A\' 以外的任何其他输入都是无效输入。但是,当我添加 OR 时,例如

System.out.print(\"What letter grade do you want to achieve for the course? \");
char desiredGrade = keyboard.next().toUpperCase().charAt(0);
    
if (desiredGrade != \'A\' || desiredGrade != \'B\') {
    System.out.println(\"Invalid input\");
    System.exit(0);
}

即使用户输入 A 或 B,它也会贯穿 if 语句。这是我遗漏的简单书写错误吗?谢谢!

  • 看来你需要&& (and)。

标签: java


【解决方案1】:

利用desiredGrade != 'A' && desiredGrade != 'B'

【讨论】:

    猜你喜欢
    • 2016-11-21
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 2017-03-21
    • 2013-12-07
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多