我正在努力正确循环编写的代码,以将整数转换为罗马数字。
我尝试实现一个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));
}
}
}
答案 0 :(得分: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"));
}