简体   繁体   中英

Why is my display method printing out the output twice?

import java.util.*;

public class Lights {
    boolean L1;
    boolean L2;

    public Lights(boolean x) {
        L1 = x;
        L2 = x;
    }

    public void displayStatus() {
        if (L1 == true) {
            System.out.println("L1 is on");
        } else if (L1 == false) {
            System.out.println("L1 is off");
        }
        if (L2 == false) {
            System.out.println("L2 is on ");
        } else if (L2 == true) {
            System.out.println("L2 is off");
        }
    }
}

class Simulator {
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        System.out.println("Do want lamps on or off");
        String s = console.nextLine();
        boolean x = true;

        if (s.equals("on")) {
            x = true;
        }

        if (s.equals("off")) {
            x = false;
        }

        Lights L1 = new Lights(x);
        Lights L2 = new Lights(x);
        L1.displayStatus();
        L2.displayStatus();
    }
}

When i call my displayStatus method, the output is printing out the same output twice. Why is that? When i just call one display method, it prints out the output for both one time. I'm trying to get it to print the output once when i call the method, but i can't understand why its printing it twice.

Why is my display method printing out the output twice?

That is because you have 2 sets of if-statements in your method.

//print once
if(...){

}
else if(...){

}
//print again
if(...){

}
else if(...){

Further more, I see 2 boolean flags in your Light object ( L1 and L2 ) and you declared 2 Light objects later on in your code. You probably want your Light class to correspond to only one light object.

Your Light class only needs one boolean for the light status:

class Light{
    private boolean lightIsOn;

    public Light(boolean status){
        this.lightIsOn = status;
    }

    public void displayStatus(){
        if(lightIsOn)
            System.out.println("Light is On");
        else
            System.out.println("Light is Off");
    }   
}

You create 2 Light objects: L1 and L2 , but your Light object always has 2 boolean attributes ( L1 and L2 as well ... very misleading) -> 4 boolean values: L1.L1, L1.L2, L2.L1, L2.L2

So when you display L1 's status, you get 2 output, based on L1.L1 and L1.L2 ... The same thing with L2 Light object. So you get 4 rows as output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM