jeudi 19 avril 2018

Beginner's issue with if statement

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

Aucun commentaire:

Enregistrer un commentaire