我有一个练习,讨论添加计划和估计的时间作为参数。
在问题中,上午10:15表示为615 (=10*60+15)。
和晚上8:15作为1215 (= 20*60+15)。
这给了我一个创建变量的想法。
我的问题是,我不能得到打印输出“列车被延误了x分钟”本身。它总是打印出“索赔赔偿”
我不认为我被允许创建除main方法和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;
}
}
我希望打印输出只显示一个条件,而不是两个条件。
发布于 2019-04-28 04:17:56
您已经满足了多个if
条件(第3个和第4个),因此,将显示两个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");
}
https://stackoverflow.com/questions/55884454
复制相似问题