首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用具有相同变量的打印一个条件而不是两个条件

如何使用具有相同变量的打印一个条件而不是两个条件
EN

Stack Overflow用户
提问于 2019-04-28 04:06:23
回答 1查看 53关注 0票数 -1

我有一个练习,讨论添加计划和估计的时间作为参数。

在问题中,上午10:15表示为615 (=10*60+15)。

和晚上8:15作为1215 (= 20*60+15)。

这给了我一个创建变量的想法。

我的问题是,我不能得到打印输出“列车被延误了x分钟”本身。它总是打印出“索赔赔偿”

我不认为我被允许创建除main方法和printTrainDelay之外的其他方法。

代码语言:javascript
复制
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;
}

}

我希望打印输出只显示一个条件,而不是两个条件。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-28 04:17:56

您已经满足了多个if条件(第3个和第4个),因此,将显示两个println

您需要使用if-else块。如果使用它,则只会执行第一个通过if条件的块

代码语言:javascript
复制
 //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");
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55884454

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档