-1

Beginner to java. Trying to make it so that my code only takes a certain letter grade input or otherwise exits the system. When I put in this code,

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);
}

it works fine and reads that any other input other than 'A' is an invalid input. However, when I add an OR such as

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);
}

it runs through the if statement even though the user inputs A or B. Is this a simple writing error that I am missing? Thanks!

joel
  • 1
  • It seems that you need `&&` (`and`). – PM 77-1 Sep 30 '22 at 17:31
  • 1
    || makes it go if either one or both is true. If you type A then `desiredGrade != 'B'` is true so it goes. If you type B then `desiredGrade != 'A'` is true so it goes. If you type anything else they're both true so it goes. See the problem? – user253751 Sep 30 '22 at 17:43

1 Answers1

0

Use:

desiredGrade != 'A' && desiredGrade != 'B'
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Sugan V
  • 89
  • 2
  • 6