有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何让这个开关只选择3个选项中的一个?

System.out.println("Please make a selection between 1 and 3");
        int choice = s.nextInt();

        switch (choice)
        {
        case 3: System.out.println("Can a brother get some fries with that?");
        case 2: System.out.println("Cheeseburger it is.... fatso");
        case 1: System.out.println("Good choice, you could use a salad");
        break;
        default: System.out.println("Not a valid selection bruh");
        }

共 (3) 个答案

  1. # 1 楼答案

    你需要休息一下;在每个案例之后

     switch (choice)
    {
        case 3: System.out.println("Can a brother get some fries with that?");
        break;
        case 2: System.out.println("Cheeseburger it is.... fatso");
        break;
       case 1: System.out.println("Good choice, you could use a salad");
       break;
       default: System.out.println("Not a valid selection bruh");
       break;
    }
    
  2. # 2 楼答案

    您缺少中断语句

  3. # 3 楼答案

    switch (choice) {
        case 3: System.out.println("Can a brother get some fries with that?"); break;
        case 2: System.out.println("Cheeseburger it is.... fatso"); break;
        case 1: System.out.println("Good choice, you could use a salad"); break;
        default: System.out.println("Not a valid selection bruh"); break;
    }
    

    我实际上只是在每个case之后添加了break,所以如果它遇到1,2,3或者没有遇到它们,它将退出你的switch