Search code examples
javalogicdo-whileexplain

Logic - Java programming do-while loops


So when you're coding in Java and doing a do-while loop, when there are multiple conditions to break the loop you have to use && (and) instead of || (or). I know that && will break the loop.

In this example, entering 1, 2, 3, or 4 breaks the loop, but why is it && !??! My Professor cant explain it..

import java.util.*;
public class ErrorTrap
{
    public static void main(String[] args)
    {
        System.out.println("Program by --");
        System.out.println();
        System.out.println("Error Traps");
        System.out.println();
        //initialize variables
        Scanner input = new Scanner(System.in);
        char year;

        //user input
            do {
                System.out.print("Please input a 1, 2, 3 or 4:  ");
                year = input.nextLine().charAt(0);

                //output
                System.out.println(num);
                System.out.println();
                }
                while(year != '1' && year != '2' && year != '3' && year != '4');          
    }//end main
}//end ErrorTrap

Solution

  • Let's say the user puts in 5

    Let's check the result:

    5 != 1 is true
    5 != 2 is true
    5 != 3 is true
    5 != 4 is true
    

    true && true && true && true is true so the loop keeps looping.

    Once, for example, the user puts in 3, we have the following :

    3 != 1 is true
    3 != 2 is true
    3 != 3 is false
    3 != 4 is true
    

    true && true && false && true is false so we break off the loop.

    Let's now say you think of using || and put in 3 :

    3 != 1 is true
    3 != 2 is true
    3 != 3 is false
    3 != 4 is true
    

    true || anything gives out true so the code doesn't respect your specifications because you want to break off when entering 2, 3 or 4


    Little rule :

    If you're using || and the first test is true, the compiler doesn't even bother testing the rest of the tests, output will be true.

    Same goes with && and first test is false.