我遇到一个问题,让构造函数中的变量显示在我的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;
}
答案 0 :(得分: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;
}
}
答案 1 :(得分:0)
在你的第二个构造函数中,你基本上没有做任何事情。由于您使用相同的变量名作为参数,因此隐藏了全局变量elaspedTime
和currentTime
。将其更改为以下内容:(添加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();
}