0

我在获取构造函数中的变量以显示在我的 main 方法的输出中时遇到问题。我可以让程序只使用方法来工作,但是,使用构造函数时会出现问题。任何朝着正确方向的帮助或提示都会很棒!

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;
    }
4

2 回答 2

0

对不起!但我没有得到这个!”但是,使用构造函数时会出现问题
能否请您提供更多详细信息!
谢谢!
谢谢!为您的详细信息。只需在第一行调用public static void main中的输入法

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

}

于 2013-08-25T18:56:38.103 回答
0

在您的第二个构造函数中,您基本上没有做任何事情。由于您使用与参数相同的变量名称,因此您的全局变量elaspedTimecurrentTime是隐藏的。将其更改为以下内容:(添加this.

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

其次,你在这个构造函数中做什么是没有意义的。在这种情况下,将 currentTime 和 elapsedTime 作为构造函数参数传递意味着您应该将它们设置为全局变量,例如:

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();
}
于 2013-08-25T18:58:28.717 回答