簡體   English   中英

為什么我的顯示方法打印輸出兩次?

[英]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();
    }
}

當我調用我的 displayStatus 方法時,輸出會打印兩次相同的輸出。 這是為什么? 當我只調用一種顯示方法時,它會一次打印輸出。 當我調用該方法時,我試圖讓它打印輸出一次,但我不明白為什么它打印兩次。

為什么我的顯示方法打印輸出兩次?

那是因為您的方法中有 2 組 if 語句。

//print once
if(...){

}
else if(...){

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

}
else if(...){

此外,我在您的 Light 對象( L1L2 )中看到了 2 個布爾標志,並且您稍后在代碼中聲明了 2 個 Light 對象。 您可能希望 Light 類只對應一個燈光對象。

你的 Light 類只需要一個布爾值來表示燈光狀態:

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

您創建了 2 個 Light 對象: L1L2 ,但您的 Light 對象始終具有 2 個布爾屬性( L1L2以及...非常具有誤導性)-> 4 個布爾值: L1.L1、L1.L2、L2.L1、L2 .L2

因此,當您顯示L1的狀態時,您將獲得 2 個輸出,基於L1.L1L1.L2 ...與L2 Light 對象相同。 所以你得到 4 行作為輸出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM