2016-06-18 40 views
-3

如何使用This post while循環工作做某些時間之間的特定的任務(例如,使用僞代碼:Java的循環和時間

while time > 05:00 && time < 16:59

我明白,我需要改變這些到輸入後整型,我只是不知道怎麼做實際的while循環

我他們改爲整數下列方式:

String hoursString = time.substring(0,1); 
String minutesString = time.substring(3,4); 

int hours = Integer.parseInt(hoursString); 

int minutes = Integer.parseInt(minutesString); 

編輯:

非常感謝大家的幫助,我帶着if語句的另一個方向去檢查小於和超過時間條件。 :)

if ((hours >= 05) && (hours <= 16) { do stuff} 

這就是我一起去的。^

+0

在Java中,同時進行表達。所以你不能使用大於。 –

+0

我認爲在java表達式中需要使用java括號,而這些表達式用作條件任意。您可以編輯要添加的問題,您是如何在計算小時和分鐘時使用它的?謝謝。 – Dilettant

回答

1

,直到滿足條件可以比較的日期......

例子:

public static void main(String[] args) { 
Scanner s = new Scanner(System.in); 
String format = TIME_FORMAT; 
boolean isDateOk = false; 
Date theDate1 = new Date(); 
Date theDate2 = new Date(); 
try { 
    theDate1 = new SimpleDateFormat(TIME_FORMAT).parse("05:00"); 
    theDate2 = new SimpleDateFormat(TIME_FORMAT).parse("16:59"); 
} catch (ParseException e1) { 
} 
String inp = ""; 
SimpleDateFormat sdf = new SimpleDateFormat(format); 
while (!isDateOk) { 
    System.out.println("Please give the desired time in this fomrat HH:mm ..."); 
    inp = s.nextLine(); 
    try { 
    Date date = sdf.parse(inp); 
    if (date.compareTo(theDate1) > 0 && date.compareTo(theDate2) < 0) { 
     isDateOk = true; 
    } 
    // date.compareTo(theDate1) // will return an int, if negative 
    // means date time is bigger than theDate1 
    } catch (ParseException e) { 
    System.err.println("invalid date..."); 
    } 
} 
// out of the while 
System.out.println("the given date was ok"); 
} 
1

定時器

你不希望使用while循環。 while循環會鎖定您的用戶界面。你應該做的是使用java.util.Timer

基本上,你會想這樣做,因爲在這個崗位Scheduling a Timer Task to Run at a Certain Time : Timer發現:

import java.sql.Date; import java.util.Timer; import 
    java.util.TimerTask; 

     public class Main { public static void main(String[] argv) throws 
     Exception { 

      Date timeToRun = new Date(System.currentTimeMillis() + numberOfMillisecondsInTheFuture); 


       Timer timer = new Timer(); 

        timer.schedule(new TimerTask() { 
        public void run() { 
         System.out.println("doing"); 
        } 
        }, timeToRun); } } 

,那麼你會剛剛結束,在你結束時間的計時器。當然,在你的具體情況下,你只需要用你想要的特定日期初始化日期對象,而不是將來使用一定的毫秒數。

+1

雖然'Timer'是一種學習的好方法,因爲[class's documentation](http://docs.oracle.com/javase/8/docs/api/java/util/Timer.html)提到你應該畢業使用['Executor'](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html),特別是['ScheduledExecutorService'](https:// docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html)。搜索堆棧溢出瞭解更多信息。 –