无法正确构建具有正确运行条件的while循环

问题描述 投票:0回答:1

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

我已经尝试实现一个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
投票

1)你的if - else if条件是多余的。您可以使用简单的if - else作为输入只能在该范围内或不在。如果你有两个或更多的范围需要检查,else if只会发生,例如:

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

2)当用户输入为Y / y时,您不需要开关块而是在while条件下使用用户输入,即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"));
}
© www.soinside.com 2019 - 2024. All rights reserved.