我正在尝试制作一个程序来计算今天和出生那天之间的天数(嗯,我还在学习,所以这个想法不是很聪明)。该程序从键盘上获取用户写入的日期并计算稍后输出的差值。我已经做了一个 getdifference 方法来计算它。
问题是,我需要一个用于日、月和年的变量(由用户输入),稍后由 getdifference 方法使用。我知道,方法中的变量是本地的,所以 eclipse 告诉我将它们转换为静态变量 - 我想这不是最好的主意,因为它们(至少我认为是这样)作为默认值启动并且答案总是 0 .
问题是 - 如何创建一个可能不是静态的并且可以在方法中使用的值?我尝试过使用 setter、getter,但我认为这可能是一种更简单的方法,只是找不到。不久前我开始编码,所以任何方向和提示将不胜感激,因为老实说我不认识任何 java 开发人员,所以不能只给别人我的代码来检查。
public class HowManyDaysTest {
static String yearinStr;
static String monthinStr;
static String dayinStr;
static String strLong;
static long daysBetween;
Temporal birthday;
public void getDifference() {
LocalDate today = LocalDate.now();
try{
birthday = LocalDate.of(Integer.valueOf(dayinStr),Integer.valueOf(monthinStr), Integer.valueOf(yearinStr));
}
catch(NumberFormatException ex) {
System.out.println("Error");
}
try{
daysBetween = ChronoUnit.DAYS.between(birthday, today); }
catch(NullPointerException e) {
System.out.println("Error"); }
strLong = Long.toString(daysBetween);
System.out.println(strLong);
System.out.println(daysBetween);
System.out.println(birthday);
}
public HowManyDaysTest() {
JFrame frame= new JFrame("How many days?");
JLabel question= new JLabel("Please enter your date of birth");
JTextField d = new JTextField("DD");
JTextField m = new JTextField("MM");
JTextField y = new JTextField("YYYY");
JLabel ans= new JLabel();
frame.setVisible(true);
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(question,BorderLayout.NORTH);
frame.add(d,BorderLayout.WEST);
frame.add(m,BorderLayout.CENTER);
frame.add(y,BorderLayout.EAST);
frame.add(ans,BorderLayout.SOUTH);
d.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent arg0) {
d.setText("");
}
@Override
public void focusLost(FocusEvent e) {
// TODO Auto-generated method stub
}
});
m.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent arg0) {
m.setText("");
}
@Override
public void focusLost(FocusEvent e) {
// TODO Auto-generated method stub
}
});
y.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent arg0) {
y.setText("");
}
@Override
public void focusLost(FocusEvent e) {
// TODO Auto-generated method stub
}
});
d.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dayinStr = d.getText();
Integer.parseInt(dayinStr);
}
});
m.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
monthinStr = m.getText();
}
});
y.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
yearinStr = y.getText();
odp.setText(strLong);
}
});
}
public static void main(String[] args) {
HowManyDaysTest app = new HowManyDaysTest();
app.getDifference();
}
}