很抱歉在错误的论坛发帖.. 请参阅:https://codereview.stackexchange.com/questions/63055/next-departure-in-java
您好我正在尝试根据Java中的当前系统时间计算下一次出发的时间。
我到目前为止还不熟悉Java的许多方面,但我已经设法让程序在大多数用例中使用switch语句和while循环,但感觉我使用了太多的变通方法来获取代码按预期工作。
下一步是我试图以一种不那么乏味和更优雅的方式完成任务。我想知道是否有人能指出我的方向如何以类似的方式完成任务,但具有java的其他功能?如arraylists,table等适合我想要完成的事情。
以下是代码:
public class TrainDepartures{
public static void main(String[] args) {
long time = System.currentTimeMillis();
int initialTime = (int) (time / (1000 * 60) % 60);
int findNextDeparture = (int) (time / (1000 * 60) % 60);
boolean foundDeparture = false;
loop: while (foundDeparture != true) {
findNextDeparture++;
switch (findNextDeparture) {
case 10:
System.out.print("Departure in " + (Math.abs(initialTime - 10)) + " min.");
break loop;
case 20:
System.out.print("Departure in " + (Math.abs(initialTime - 20)) + " min.");
break loop;
case 30:
System.out.print("Departure in " + (Math.abs(initialTime - 30)) + " min.");
break loop;
case 40:
System.out.print("Departure in " + (Math.abs(initialTime - 40)) + " min.");
break loop;
case 50:
System.out.print("Departure in " + (Math.abs(initialTime - 50)) + " min.");
break loop;
case 52:
System.out.print("Departure in " + (Math.abs(initialTime - 52)) + " min.");
break loop;
case 55:
System.out.print("Departure in " + (Math.abs(initialTime - 55)) + " min.");
break loop;
case 56:
System.out.print("Departure in " + (Math.abs(initialTime - 56)) + " min.");
break loop;
case 57:
System.out.print("Departure in " + (Math.abs(initialTime - 57)) + " min.");
break loop;
}
}
}
}
答案 0 :(得分:0)
您可以使用
替换整个switch
语句
System.out.print("Departure in " + (Math.abs(initialTime - findNextDeparture)) + " min.");
您以完全相同的方式处理每个案例,因此您不需要switch
的复杂性或详细程度。
(例如,如果findNextDeparture==53
以及您尚未列出的任何其他值,则假设您还要打印该行。)
答案 1 :(得分:0)
以下是您可以尝试的内容。使用String格式更改switch语句:
final int departureTime = Math.abs(initialTime - findNextDeparture);
String result = String.format("Departure in %d min", departureTime);
System.out.print(result);
Switch语句的输出和上面的代码是一样的。
答案 2 :(得分:0)
public class TrainDepartures
{
public static void main(String[] args)
{
long time = System.currentTimeMillis();
int initialTime = (int) (time / (1000 * 60) % 60);
//these are the minutes you care about.
int[] departureTimes = new int[]{10,20,30,40,50,52,55,56,57};
int lastValidId = 0;
int timeDiff = 0;
for (int d = 0; d < departureTimes.length; d++)
{
if ( initialTime < departureTimes[d])
{
//keep track of the smallest value greater than the current time.
lastValidId = d;
timeDiff = (departureTimes[lastValidId] - initialTime);
if (d == 0)//first time, were done.
break;
}
else
{
timeDiff = (departureTimes[lastValidId] - initialTime);
if ( timeDiff < 0 )
{
//wrap around when you cross into the next hour...
timeDiff = (departureTimes[0]+60) - initialTime;
}
break;
}
}
System.out.print("Departure in " + timeDiff + " min.");
}
}