You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java方法循环问题:getYNConfirm方法逻辑错误致流程异常

修复10元店商品总价计算程序的逻辑错误

修复后的getYNConfirm方法

public static boolean getYNConfirm(Scanner pipe, String prompt) {
    boolean done = false;
    boolean response = false;
    String YNResp = "";

    do {
        System.out.println(prompt);
        YNResp = pipe.nextLine().trim();

        if (YNResp.equalsIgnoreCase("Y")) {
            done = true;
            response = false; // Y表示继续添加,返回false(需求定义:false=Yes)
        } else if (YNResp.equalsIgnoreCase("N")) {
            done = true;
            response = true; // N表示停止添加,返回true(需求定义:true=No)
        } else {
            System.out.println("Please input Y/N. You input: " + YNResp);
        }
    } while (!done);

    return response;
}

修复后的主程序

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    double itemPrice = 0;
    double totalPrice = 0;
    boolean stopAdding = false;

    do {
        itemPrice = SafeInput.getRangedDouble(in, "Please insert the item price", 0.50, 9.99);
        totalPrice += itemPrice;

        stopAdding = SafeInput.getYNConfirm(in, "Do you have more items? (Y/N)");

    } while (!stopAdding);

    System.out.printf("Your total price is $%.2f%n", totalPrice);
}

错误点说明

原getYNConfirm方法问题:

  • 返回类型不符:需求要求返回boolean,原方法返回String,导致主程序无法正确判断用户选择
  • 分支逻辑错误:第二个if未改为else if,输入Y时会触发后续else分支的错误提示
  • 多余输入读取:else分支中额外调用pipe.nextLine(),会吃掉下一次输入,引发交互异常
  • 提示内容错误:错误提示显示的是多余读取的内容,而非用户实际输入的无效值
  • 未处理空格:添加trim()避免用户输入空格导致的无效判断

原主程序问题:

  • 总价累加错误:原代码每次创建新变量存储总价,未实现累加逻辑,改为totalPrice += itemPrice修复
  • 无效输入操作:删除错误的in.NextLine()(大小写错误+多余读取),避免打乱输入流
  • 循环控制失效:原程序未将getYNConfirm的返回值赋值给控制变量,导致循环条件永远不变
  • 输出格式错误:原代码直接拼接字符串,改为printf的%.2f占位符实现保留2位小数的格式化输出
  • 输出时机错误:原程序每次循环都输出总价,改为用户停止添加后输出最终结果

内容的提问来源于stack exchange,提问作者user20244229

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 10:05:21