为了账号安全,请及时绑定邮箱和手机立即绑定

难以适当地构建具有正确条件的做而循环运行

难以适当地构建具有正确条件的做而循环运行

潇潇雨雨 2022-09-07 21:51:42
我正在努力正确循环我编写的代码以将整数转换为罗马数字。我尝试实现一个 do while 循环来运行代码,从“请输入一个整数”开始,在我的 switch 语句之后结束,while 部分是:while(大小写 “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));        }          }}
查看完整描述

1 回答

?
蝴蝶不菲

TA贡献1810条经验 获得超4个赞

1)您的条件是多余的。您可以使用简单,因为输入只能在该范围内进行。 仅当您要检查两个或多个范围时才有意义,例如if - else ifif - elseelse 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"));

}


查看完整回答
反对 回复 2022-09-07
  • 1 回答
  • 0 关注
  • 121 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号