我有这个练习,它讨论将计划和估计的时间添加为参数。
在问题中,上午10:15表示为615(= 10 * 60 + 15)。
然后是晚上12:15(= 20 * 60 + 15)的8:15。
这给了我一个从中创建变量的想法。
我的问题是我自己无法获得打印输出“火车延迟了x分钟”。它始终以“索赔补偿”打印出来
除主方法和printTrainDelay之外,我不允许创建其他方法。
public static void main (String[] args){
int hourOne = 10;
int hourTwo = 20;
int min = 60;
int second = 15;
int timeOne = hourOne * min + second;
int timeTwo = hourTwo * min + second;
printTrainDelay(timeOne,timeTwo);
}
public static int printTrainDelay (int scheduledTimes, int estimatedTimes) {
if (estimatedTimes == scheduledTimes){
System.out.println("The train is on time");
}
if (estimatedTimes < 1) {
System.out.println("The train is delayed by 1 minute");
}
if (estimatedTimes > 1) {
System.out.println("The train is delayed by x minute");
}
if estimatedTimes > 30){
System.out.println("Claim compensation");
}
return estimatedTimes;
}
}
我希望打印输出仅显示一种情况,而不是两种情况。
答案 0 :(得分:1)
您已经满足多个if
条件( 3rd 和 4th ),因此,同时显示了两个println
。>
您需要使用if-else
块。如果使用它,则只会执行具有第一个通过if
条件的块
//you can extract time difference to a variable to avoid recalculating it
int timeDifference = scheduledTimes - estimatedTimes;only once
if (timeDifference == 0){
System.out.println("The train is on time");
} else if (timeDifference < 1) {
System.out.println("The train is delayed by 1 minute");
} else if (timeDifference > 1) {
System.out.println("The train is delayed by x minute");
} else if (timeDifference > 30) {
System.out.println("Claim compensation");
}