我当时的 if 语句不起作用 - 收到一条错误消息
My if-statements for the time are not working - getting an error message
我正在尝试使用 if 语句根据当前时间向用户显示问候消息。我已经设置了当前时间,但无法将其用于 if 语句。
public class MyFrame extends JFrame {
public MyFrame() {
super("Greeting");
setbounds(200, 200, 200, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("hh");
JTextArea tx = new JTextArea(10,5);
String myTime = sdf.format(cal.getTime());
if (myTime < 12am && myTime > 12pm)
tx.append("Good Morning");
}
if (myTime <12am && myTime > 12pm)
tx.append("Good Afternoon");
}
JPanel pane = new JPanel();
pane.add(tx);
add(pane);
setVisible(true);
}
public static void main(String [] args) {
new MyFrame();
}
}
这个说法不对
if (myTime < 12am && myTime > 12pm)
你不能像那样比较字符串,你可以获取 24 小时格式的时间,然后将其解析为整数以便进行比较。
关于你的守卫,试试:
if (myTime < twelveAM)
myGreeting = "Good Morning"
} else {
myGreeting = "Good Afternoon"
}
tx.append(myGreeting);
如果 myTime 小于 twelveAM
引用的值,则将附加 'Good Morning'。如果myTime不小于twelveAM
所引用的值,流程流将通过守卫并追加'Good Afternoon'.
特别注意类型转换,这是在你的守卫中进行比较之前必须做的,如下面的评论所述。
我正在尝试使用 if 语句根据当前时间向用户显示问候消息。我已经设置了当前时间,但无法将其用于 if 语句。
public class MyFrame extends JFrame {
public MyFrame() {
super("Greeting");
setbounds(200, 200, 200, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("hh");
JTextArea tx = new JTextArea(10,5);
String myTime = sdf.format(cal.getTime());
if (myTime < 12am && myTime > 12pm)
tx.append("Good Morning");
}
if (myTime <12am && myTime > 12pm)
tx.append("Good Afternoon");
}
JPanel pane = new JPanel();
pane.add(tx);
add(pane);
setVisible(true);
}
public static void main(String [] args) {
new MyFrame();
}
}
这个说法不对
if (myTime < 12am && myTime > 12pm)
你不能像那样比较字符串,你可以获取 24 小时格式的时间,然后将其解析为整数以便进行比较。
关于你的守卫,试试:
if (myTime < twelveAM)
myGreeting = "Good Morning"
} else {
myGreeting = "Good Afternoon"
}
tx.append(myGreeting);
如果 myTime 小于 twelveAM
引用的值,则将附加 'Good Morning'。如果myTime不小于twelveAM
所引用的值,流程流将通过守卫并追加'Good Afternoon'.
特别注意类型转换,这是在你的守卫中进行比较之前必须做的,如下面的评论所述。