【问题标题】:Switch statement with do while loop带有 do while 循环的 switch 语句
【发布时间】:2021-03-08 22:00:16
【问题描述】:

我正在尝试编写一个代码,要求用户输入一个数字,每个数字都有一条消息,例如:

1-2 Buckle your shoes
3-4 Shut the door
5-6 Pick up sticks
7-8 Lay them straight
9-10 Begin again

但如果用户输入 9 或 10,它会再次要求一个数字来重复它。

当我尝试输入 9 或 10 时,它不会重复。有人可以帮忙吗?

import java.util.Scanner;

    public class javaQuiz4try2{
    public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    int number;

    boolean x = false;
    do{
        System.out.println("Enter a number(1-10)");
    number=sc.nextInt();
    
    switch(number){
    case 1: 
        case 2:
        System.out.println("Buckle my shoe");
        x=true;
        break;
    case 3:
        case 4:
        System.out.println("Shut the door");
        x=true;
        break;
    
    case 5:
        case 6:
        System.out.println("Pick up sticks");
        x=true;
        break;
    case 7:
        case 8:
        System.out.println("Lay them straight");
        x=true;
        break;  
    case 9:
    case 10:
        System.out.println("Begin again");
        x=false;
        break;
        }
            }while(number<=9);
        
        }
}

【问题讨论】:

  • 欢迎来到 StackOverflow。您需要包含相关代码和解决此问题的尝试。如果您不知道如何编写循环,Google 是您的朋友。

标签: loops switch-statement


【解决方案1】:

在伪代码中:

永远循环:

  • 征求用户意见
  • 捕获输入
  • 如果输入介于 1 和 8 之间(含)退出循环
  • 显示“无效输入”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-16
    • 2022-01-03
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 2019-12-17
    • 1970-01-01
    相关资源
    最近更新 更多