2016-06-18 104 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)。搜索堆栈溢出了解更多信息。 –