0

我有一個問題,在構造函數中顯示在我的主要方法的輸出中的變量。我可以讓程序只使用方法來工作,但是,使用構造函數時會出現問題。任何幫助或提示正確的方向將是偉大的!從重載構造函數調用變量

public class Time { 
    public static void main (String[] args) { 
     TimeCalculations time1 = new TimeCalculations(); 
     System.out.println(time1.getCurrentTime()); 
     System.out.println(time1.getElaspedTime()); 

    public static long input() { 
     Scanner input = new Scanner(System.in); 
     System.out.println("Enter a time"); 
     return TimeCalculations.elaspedTime = input.nextLong();} 

class TimeCalculations { 
    public long currentTime; 
    public static long elaspedTime; 


public TimeCalculations() { 

    currentTime = System.currentTimeMillis(); 
    this.currentTime = currentTime; 
    } 

    public TimeCalculations(long currentTime, long elaspedTime) { 
     elaspedTime = currentTime -Time.input(); 
    } 

    public long getCurrentTime() { 
    return this.currentTime; 
    } 

public long getElaspedTime() {  
    return TimeCalculations.elaspedTime; 
    } 
+0

你有什麼確切的問題? – Kon

+0

我可以得到我的currentTime變量(時間以毫秒爲單位)顯示在我的輸出中,但不是elaspedTime變量。在我的第二個構造函數中,我甚至試圖將elaspedTime設置爲給定值,但仍然沒有返回到輸出。我沒有包含我的輸入法來節省空間。 – user2715988

回答

0

對不起!但我沒有得到這個! 「但是,使用構造函數時會出現問題
請您詳細介紹一下!
謝謝!
謝謝!爲您的細節。 只是調用公共靜態無效的主要在第一線

import java.util.*; 
public class Time{ 
public static void main(String[] args) { 
    input(); 
    TimeCalculations time1 = new TimeCalculations(); 
    System.out.println(time1.getCurrentTime()); 
    System.out.println(time1.getElaspedTime()); 
} 
public static long input() { 
    Scanner input = new Scanner(System.in); 
    System.out.println("Enter a time"); 
    return TimeCalculations.elaspedTime = input.nextLong();} 

} 

class TimeCalculations { 
public long currentTime; 
public static long elaspedTime; 


public TimeCalculations() { 
    currentTime = System.currentTimeMillis(); 
    this.currentTime = currentTime; 
} 

public long getCurrentTime(){ 
    return this.currentTime; 
} 

public long getElaspedTime() {  
    return TimeCalculations.elaspedTime; 
} 

}

+0

爲什麼將elapsedTime用作靜態變量? –

+0

是的。我做了同樣的程序,但是使用常規方法返回語句。從那裏,我能夠得到每個價值到我的輸出。當我將方法改爲構造函數時,我無法將值傳遞給其他類。這些幫助有用? – user2715988

+0

當我將其更改爲非靜態時,出現編譯錯誤「無法對非靜態字段進行靜態引用」。在我的第二個構造函數中。 – user2715988

0

在你的第二個構造函數,你基本上是什麼都不做輸入法。由於您使用的變量名稱與參數相同,因此您的全局變量elaspedTimecurrentTime處於隱藏狀態。將其更改爲以下幾點:(加this.

public TimeCalculations(long currentTime, long elaspedTime) { 
    this.elaspedTime = currentTime -Time.input(); 
} 

其次,它沒有任何意義,你在這個構造在做什麼。在這種情況下,通過currentTime的和elapsedTime作爲構造PARAMS意味着你應該將它們設置爲全局變量,如:

public TimeCalculations(long currentTime, long elaspedTime) { 
    this.elaspedTime = elapseTime; 
    this.currentTime = currentTime; 
} 

在你的第一個構造函數,你只是設置currentTime的兩倍。改成類似的東西:

public TimeCalculations() { 
    // since there is no local var named currentTime, you don't need 
    // to put this. 
    currentTime = System.currentTimeMillis(); 
} 
+0

感謝您的幫助! – user2715988