我正在尝试收集小时。这似乎在此类课程中起作用。现在,我想在另一个类中使用intTime进行一些计算。如何返回intTime。
返回实例的属性时,我尝试使用相同的原理,但是时间与我使用的任何对象都不相关。 getIntTime是否可行?
import java.text.SimpleDateFormat;
import java.util.*;
public class Time extends Database{
public Time(){
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat ("HH:mm:ss");
String stringTime = sdf.format (cal.getTime());
int intTime = 0;
stringTime = stringTime.substring(3,5); // retrieve the minutes (is recorded as string)
intTime = Integer.parseInt(stringTime);
}
public String getStringTime() {
return intTime;
}
public static void main (String[] args) {
}
}
最佳答案
您需要将intTime定义为类成员。在您的代码中,intTime仅在构造函数内部“存在”。
import java.text.SimpleDateFormat;
import java.util.*;
public class Time extends Database{
// class member defined in the class but not inside a method.
private int intTime = 0;
public Time(){
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat ("HH:mm:ss");
String stringTime = sdf.format (cal.getTime());
// vars defined here, will be gone when method execution is done.
stringTime = stringTime.substring(3,5); // retrieve the minutes (is recorded as string)
// setting the intTime of the instance. it will be available even when method execution is done.
intTime = Integer.parseInt(stringTime);
}
public String getStringTime() {
return intTime;
}
public static void main (String[] args) {
// code here
}
}