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

Java控制台整数输入分支执行代码的问题排查

问题解决:根据输入整数执行分支代码

原代码核心错误

  • main方法缺少static修饰符,JVM无法识别为程序入口
  • 条件判断误用赋值运算符=(而非比较运算符==),且错误地将int类型的choice与字符串"1"做类型不匹配的比较
  • 表示数量的变量使用double类型,不符合业务场景(数量应为整数)

修正后的完整代码

import java.util.Scanner;
public class OrderApp {
    // 单人/多人派对选择逻辑
    public static void main(String[] args) {
        // 数量用int类型更贴合实际场景
        int burger; 
        int fries; 
        int soda; 
        int groupNumber;

        Scanner input = new Scanner(System.in);

        // 打印菜单选项
        System.out.println("Menu");
        System.out.println("----------------");
        System.out.println("1 - Solo party");
        System.out.println("2 - Multiple Party");
        System.out.print("--->");
        int choice = input.nextInt();
        input.nextLine(); // 读取输入后的换行符,避免后续输入异常

        // 正确的分支判断逻辑
        if (choice == 1) {
            // 单人派对处理逻辑
            System.out.print("Enter the amount of burgers>>>>:");
            burger = input.nextInt();
        } else if (choice == 2) {
            // 多人派对处理逻辑
            System.out.print("Enter Amount of Party Members: ");
            groupNumber = input.nextInt();
        } else {
            // 处理非法输入的情况
            System.out.println("Invalid choice, please enter 1 or 2");
        }

        input.close(); // 关闭Scanner资源,避免资源泄漏
    }
}

关键修改说明

  1. 修复程序入口:给main方法添加static修饰符,public static void main(String[] args)是Java程序的标准入口格式,没有staticJVM无法启动程序
  2. 修正条件判断:
    • 替换choice = "1"为choice == 1:==用于数值类型的相等比较,且直接与整数1对比(choice是int类型,不能和字符串比较)
    • 新增else if (choice == 2)明确匹配多人派对选项,同时添加else分支处理用户输入非1/2的情况,提升程序健壮性
  3. 优化变量类型:将burger、groupNumber等表示数量的变量从double改为int,符合实际业务逻辑(数量应为整数)
  4. 资源管理:添加input.close()关闭Scanner对象,释放相关资源

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 01:37:22