2017-02-22 62 views
-1

下午!我在課堂「電視」中遇到了一些麻煩。我基本上試圖完成的是每當調用該方法時,我想要切換powerStatus的值。實際和正式的方法列表長度不同

/** 
* @author Thomas Samuel 
* @version 1.0 
* @since 22/02/2017 
* <h1>Television Remote/Lab Sheet 2</h1> 
* <p1>The following program is made for a television remote to control power, channel information, and volume.</p1> 
*/ 
class Television { 
    Television Television = new Television(); 
    boolean powerStatus = false; 
    int currentChannel; 
    int currentVolume = 50; 
    boolean togglePower(boolean powerStatus) { 
     if(powerStatus = false) { 
      powerStatus = true; 
     } else if(powerStatus = true) { 
      powerStatus = false; 
     } 
     return powerStatus; 
    } 
    boolean getPowerStatus(boolean powerStatus) { 
    return powerStatus; 
    } 
} 
public class Controller { 
    public static void main(String[] args) { 
     Television.togglePower(); 
    } 
} 

我收到的錯誤是如下:

Controller.java:27: error: method togglePower in class Television cannot be applied to given types; 
     Television.togglePower(); 
       ^
    required: boolean 
    found: no arguments 
    reason: actual and formal argument lists differ in length 
1 error 
+0

當你調用'togglePower'方法時,你有**沒有通過**'boolean'參數。 –

+1

'電視臺{電視電視=新電視(); ......爲什麼你將'Television'的一個實例實例化爲它自身的非靜態成員?你爲什麼要將一個變量命名爲它的類?這些都是你沒有理解一些基本原理的指標,並且使你的代碼非常難以閱讀。例如,在你的主要方法'Television.togglePower();'看起來像一個靜態方法調用,但它不是。它的作用只是因爲你的名字「電視」超載。 –

+0

接下來,您將得到一條消息,指出無法從靜態上下文中引用非靜態方法。 –

回答

1

,因爲你叫togglePower沒有參數,你會得到一個錯誤,但這種方法需要boolean參數。

更改togglePower方法不採取任何參數,因爲它已經擁有powerStatus變量:

boolean togglePower() { 

     powerStatus = !powerStatus; 

     return powerStatus; 
    } 

以同樣的方式,這是沒有意義的一個簡單的getter方法取一個參數,所以嘗試:

boolean getPowerStatus() { 
     return powerStatus; 
    } 
0

請仔細閱讀該代碼仔細看,你需要改變什麼

class Television { 
    boolean powerStatus = false; 
    int currentChannel; 
    int currentVolume = 50; 
    boolean togglePower() { 
     powerStatus = !powerStatus; 
     return powerStatus; 
    } 
    boolean getPowerStatus() { 
     return powerStatus; 
    } 
} 
public class Controller { 
    public static void main(String[] args) { 
     Television tv = new Television(); 
     tv.togglePower(); 
     System.out.println(tv.getPowerStatus()); 
    } 
} 

我將實例化移入主方法,並更改togglePower以使用邏輯「not」切換布爾值。

+0

你的代碼不太好。您的getPowerStatus方法當前正在將傳入的值返回給方法,並且togglePower方法不會切換電視上的電源。 –

+0

對不起,我忽略了從方法聲明中刪除不需要的參數。固定。 –

相關問題