0

I'm having trouble figuring out this if statement in this code:

import java.util.Scanner;

class TrafficSignal2 {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        char approachingGreen;
        char safeToProceed;
        char officerDirectingNotToProceed;

        System.out.print("Are you approaching a green light? (Y/N) ");
        approachingGreen = keyboard.findWithinHorizon(".", 0).charAt(0);

        System.out.print("Is it safe to proceed? (Y/N) ");
        safeToProceed = keyboard.findWithinHorizon(".", 0).charAt(0);

        System.out.print("Is is a traffic officer directing you not to proceed? (Y/N) ");
        officerDirectingNotToProceed = keyboard.findWithinHorizon(".", 0).charAt(0);

        if ((approachingGreen == 'Y' || approachingGreen == 'y') && 
                (safeToProceed == 'Y' || safeToProceed == 'y') && 
                (officerDirectingNotToProceed != 'Y' && officerDirectingNotToProceed != 'y')) {
            System.out.println("Go");
        } else {
            System.out.println("Stop");
        }

        keyboard.close();
    }

}

source (https://users.drew.edu/bburd/BeginProg/tryitout/Chapter10.html#yesyes)

Why doesn't the code work when I use the || logical operator instead of the && in

(officerDirectingNotToProceed != 'Y' && officerDirectingNotToProceed != 'y')

When I use || it tells the user to 'Go' when it should say 'Stop' right?

What am I seeing wrong?

Thank you

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880

2 Answers2

0
(officerDirectingNotToProceed != 'Y' || officerDirectingNotToProceed != 'y')

is guaranteed to evaluate to true, no matter what character you store in officerDirectingNotToProceed. Every character is either not equal to Y or not equal to y.

You have an extra Not in your logic hidden in the variable name. I would change that to officerDirectingToStop and reverse the logic where you set that variable. That will simplify how you parse expressions involving that variable.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
0

Based on the if statement

  1. (approachingGreen == 'Y' || approachingGreen == 'y') will return true if Y/y
  2. (safeToProceed == 'Y' || safeToProceed == 'y') will return true if Y/y
  3. (officerDirectingNotToProceed != 'Y' && officerDirectingNotToProceed != 'y') will return true if N/n but will return false if Y/y

So on the third statement I suggest you use || as this is an OR statement which tells that if there is one true then its true while && this is an AND statement which tells that if there is one false then it is false

Adam Kipnis
  • 10,175
  • 10
  • 35
  • 48