我在這里有這個代碼:

但我收到錯誤訊息:
運算子 < 對于引數型別(s)LocalTime, int 未定義
這是為什么?我該如何修復代碼?
這是作為文本的代碼:
import java.time.LocalTime;
public class Services {
public static void main(String[] args){
LocalTime t = LocalTime.now();
if (t >=0 && t<12){
System.out.println("Good Morning!");
}
else if (t>=12 && t<18)
{
System.out.println("Good Afternoon!");
}
else{
System.out.println("Hello Neel ,how may I help you");
}
}
}
uj5u.com熱心網友回復:
比較物件
你不能使用<任何東西不是像其他的原語int。使用compareTo來代替。
就像first.compareTo(second),結果要么
- 負(如果較小),
0(如果相等)或- 正大于 0(如果更大)。
所以相當于 tofirst < second是first.compareTo(second) < 0。
LocalTime特別是比較
對于java.time API,還有像isBefore和isAfter這樣的特殊方法,它們使這種比較更加簡單。
LocalTime 對比 int
此外,您無法將高級物件LocalTime與普通int. 看一下
LocalTime.of(12, 0)
和類似的方法。
還有一些特殊的預先創建的常量,例如LocalTime.MIDNIGHTand LocalTime.NOON。
把所有東西放在一起
如果您遵循這兩個建議,則固定代碼可能如下所示:
LocalTime t = LocalTime.now();
if (t.isAfter(LocalTime.MIDNIGHT) && t.isBefore(LocalTime.NOON)) {
System.out.println("Good Morning!");
} else if (t.isAfter(LocalTime.NOON) && t.isBefore(LocalTime.of(18, 0))) {
System.out.println("Good Afternoon!");
} else {
System.out.println("Hello Neel, how may I help you");
}
理想情況下,您還可以引入快速幫助方法,例如
private static boolean isBetween(LocalTime start, LocalTime time, LocalTime end) {
return time.isAfter(start) && time.isBefore(end);
}
進一步簡化代碼:
LocalTime t = LocalTime.now();
if (isBetween(LocalTime.MIDNIGHT, t, LocalTime.NOON)) {
System.out.println("Good Morning!");
} else if (isBetween(LocalTime.NOON, t, LocalTime.of(18, 0))) {
System.out.println("Good Afternoon!");
} else {
System.out.println("Hello Neel, how may I help you");
}
uj5u.com熱心網友回復:
將您的代碼翻譯成有用的東西的直接方法是
LocalTime t = LocalTime.now();
int h = t.getHour();
然后比較'h'。
對于更復雜的情況,例如,如果您想檢查是否在 12:30 之前,請查看類似的結構
t.isBefore(LocalTime.of(12, 30))
或者可能
!LocalTime.of(12, 30).isAfter(t);
(兩者的區別在于準確時間的決定12:30)
uj5u.com熱心網友回復:
public static void main(String[] args) {
LocalTime t = LocalTime.now();
int h = t.getHour();
if (h >= 0 && h < 12) {
System.out.println("Good Morning!");
} else if (h >= 12 && h < 20) {
System.out.println("Good Afternoon!");
} else {
System.out.println("Hello Neel ,how may I help you");
}
}
}這為我作業
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/385664.html
