我有一个开始时间(在这种情况下是9点钟),并且有一定的小时数被添加到它,然后需要计算当前时间。我正在使用的当前方法是添加传递给原始时间的小时数,然后按模数加12,如下所示:timeAndHoursPassed % 12 = currentTime
这在所有情况下都适用,除非添加的时间可被12整除,在这种情况下我得到当前时间为零而不是12.我该如何解决这个问题?另外,如果可能的话,我宁愿使用一些基本的数学,而不是使用GregorianCalender类。
感谢您提前提供的任何帮助。
我的代码如下:
package week11;
import java.util.Scanner;
public class PassingTrains {
static int currentTime = 9, firstDistance = 0, secondDistance = 0, firstSpeed = 40, secondSpeed;
static Scanner input = new Scanner(System.in);
public static String passTime(){
System.out.print("Enter the speed of the passenger train: ");
secondSpeed = input.nextInt();
while (currentTime < 11) {
firstDistance += firstSpeed;
currentTime++;
}
while (firstDistance > secondDistance) {
firstDistance += firstSpeed;
secondDistance += secondSpeed;
currentTime++;
}
if (firstDistance == secondDistance){
return ("at " + currentTime % 12);
} else {
return ("between " + (currentTime - 1) % 12 + " o'clock and " + currentTime % 12);
}
}
public static void main(String[] args) {
System.out.println("The passenger train passed the freight train at " + passTime() + " o'clock");
System.out.println("The freight train was traveling " + firstSpeed + " mph");
System.out.println("The passenger train was traveling at " + secondSpeed + " mph");
}
}
答案 0 :(得分:1)
分为两部分:
示例代码:
currentTime += elapsedTime % 24;
if(currentTime > 12)
{
currentTime -= 12;
}
更新:OP的更正代码
public class PassingTrains
{
static int currentTime = 9, firstDistance = 0, secondDistance = 0,
firstSpeed = 40, secondSpeed, elapsedTime;
static Scanner input = new Scanner(System.in);
public static String passTime()
{
System.out.print("Enter the speed of the passenger train: ");
secondSpeed = input.nextInt();
while (currentTime < 11)
{
firstDistance += firstSpeed;
currentTime++;
}
while (firstDistance > secondDistance)
{
firstDistance += firstSpeed;
secondDistance += secondSpeed;
elapsedTime++; // changed this
}
// added the next two lines
currentTime += elapsedTime % 24;
currentTime = (currentTime > 12) ? currentTime - 12 : currentTime;
if (firstDistance == secondDistance)
{
return ("at " + currentTime); // fixed this
}
else
{
return ("between " + ((currentTime - 1 == 0) ? 12 : currentTime - 1) + " o'clock and " + currentTime); \\fixed this
}
}
public static void main(String[] args)
{
System.out.println("The passenger train passed the freight train at "
+ passTime() + " o'clock");
System.out.println("The freight train was traveling " + firstSpeed
+ " mph");
System.out.println("The passenger train was traveling at "
+ secondSpeed + " mph");
}
}