首页 > 解决方案 > 我被困在一个 Java 项目上,我的 if 语句中的所有场景都在不断计算

问题描述

我正在研究一个点系统计算器,只是学习更多关于 Java 等的知识,但我遇到了一个问题,当我尝试输入我的一个场景数量时,它会在我的 if 语句中打印所有可能的场景。任何帮助将不胜感激,谢谢!

    double basepoints = 0.00;
    double spend = 0.00;
    double adjpnt = 0.00;

    //Prompts the user for their total spend in $, this will calculate the point system.
    //In this scenario the customer is incentivised to spend more money at one time due to
    // gaining exponentially more points based on spend.
    System.out.println("Enter Your Total Spend.");

    spend = scan.nextDouble();
    basepoints = (spend * 10);


    System.out.println("Your base points for this purchase is " + (Math.round(basepoints) )+ ". Calculating the bonuses for this purchase...");
    System.out.println("");
    if (spend < 20){
        adjpnt = (basepoints);
        System.out.println("You don't receive any bonuses this time. Sorry that you're poor. You have added " + adjpnt + " points into your account. Have a nice day.");
    }if (spend < 50 || (spend > 20)){
        adjpnt = (basepoints * 1.25);
        System.out.println("We have increased your point gain this purchase by a quarter.  " + adjpnt + " points have been added to your account. Have a nice day.");
    }if (spend < 100 || (spend > 50));{
        adjpnt = (basepoints * 1.5);
        System.out.println("Decent purchase. We're gonna throw in a little extra for you, 1.5x the amount of points to be exact.  " + adjpnt + " points have been added to your account. Have a nice day.");
    }if (spend < 200 || (spend > 100));{
        adjpnt = (basepoints * 1.75);
        System.out.println("Have 1.75x the extra points on us.  " + adjpnt + " points have been added to your account. Have a nice day.");
    }if (spend == 69){
        System.out.println("nice.");
    }

标签: javaif-statement

解决方案


除了提到的 with||和 missing问题之外else,还有一些额外的;afterif语句完全忽略了任何条件。

因此,必须修正错别字,并简化语句,else以定义不重叠的范围并仅选择 ; 的特定值adjpntnice适当时应检查条件:

System.out.println("Your base points for this purchase is " + (Math.round(basepoints) )+ ". Calculating the bonuses for this purchase...\n");
if (spend < 20) {
    adjpnt = basepoints;
} else if (spend < 50) {
    adjpnt = basepoints * 1.25;
} else if (spend < 100) {
    adjpnt = basepoints * 1.5;
    if (spend == 69) {
        System.out.println("nice.");
    }
} else if (spend < 200) {
    adjpnt = basepoints * 1.75;
} else { // this needs to be added to assign bonus correctly
    adjpnt = basepoints * 2;
}

推荐阅读