【问题标题】:Trouble appropriately constructing do while loops with correct conditions to run无法正确构建运行条件正确的 do while 循环
【发布时间】:2019-03-28 16:39:33
【问题描述】:

我正在努力正确循环我编写的将整数转换为罗马数字的代码。

我尝试实现一个 do while 循环来运行从“请输入一个整数”开始并在我的 switch 语句之后结束的代码,while 部分是:while(case "y" || "Y" == true ) 任何帮助将不胜感激。我已经搜索了几个小时之前关于堆栈溢出的帖子,但找不到任何有用的东西。

公开课项目8 {

/**
 * Constructor for objects of class Project4
 */
public static void main(String[] args) {
    System.out.println("Welcome to my integer  Roman numeral conversion program");
    System.out.println("------------------------------------------------------");
    System.out.println(" ");
    Scanner in = new Scanner (System.in);
    System.out.print("Enter an integer in the range 1-3999 (both inclusive): ");
    int input = in.nextInt();
    if (input < 0 || input > 3999){
        System.out.println("Sorry, this number is outside the range.");
        System.out.println("Do you want to try again? Press Y for yes and N for no: ");
            String userInput = in.next();
                switch (userInput) {
                 case "N":
                 case "n":
                 System.exit(0);
                 break;

                 case "Y":
                 case "y":
                break;
                }   
            } 
    else if (input > 0 && input < 3999); 

      { System.out.println(Conversion.Convert(input));
        }          
}

}

【问题讨论】:

    标签: java loops switch-statement


    【解决方案1】:

    1) 您的if - else if 条件是多余的。您可以使用简单的if - else,因为输入只能在该范围内。 else if 仅在您有两个或更多范围要检查时才有意义,例如

    if(input > 0 && input < 3999){ 
      ...
    } 
    else if (input > 4000 && input < 8000){ 
    ... 
    } 
    else { 
    ...
    } 
    

    2) 您不需要切换块,而是在您的 while 条件中使用用户输入,因为您希望在用户输入为 Y/y 时继续循环,即 while(userChoice.equals("Y"))

    3) 使用do - while 循环,因为您希望您的应用程序至少按时运行

    public static void main(String[] args) {
    
        System.out.println("Welcome to my integer  Roman numeral conversion program");
        System.out.println("------------------------------------------------------");
        System.out.println(" ");
    
        Scanner in = new Scanner (System.in);
        String choice;
        do{
            System.out.print("Enter an integer in the range 1-3999 (both inclusive): ");
            int input = in.nextInt();
            if(input > 0 && input < 3999){
                System.out.println(Conversion.Convert(input));
            }
            else{
                System.out.println("Sorry, this number is outside the range.");
            }
            System.out.println("Do you want to try again? Press Y for yes and N for no: ");
            choice = in.next();
        }while(choice.equals("Y") || choice.equals("y"));
    }
    

    【讨论】:

    • 感谢您抽出宝贵时间帮助我改进代码并更好地理解循环。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多