如果用户选择了应终止的两个选项之一,如果用户选择无效选项保持循环,直到选择了其中一个选项,则需要能够循环
import java.util.Scanner;
public class conversion {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Which conversion do you want?");
System.out.println("Pounds to Kilograms(enter 1)");
System.out.println("Kilograms to Pounds(enter 2)");
double kilograms, pounds;
int choice = input.nextInt();
while(){
if(choice == 1){
System.out.println("What weight value do you want converted?");
pounds = input.nextDouble();
kilograms = pounds / 2.20462;
kilograms = Math.round(kilograms * 100.0) / 100.0;
System.out.println( +pounds+ " pounds is equal to " +kilograms+ " kilograms");
}
else if(choice == 2){
System.out.println("What weight value do you want converted?");
kilograms = input.nextDouble();
pounds = kilograms/0.453592;
pounds = Math.round(pounds * 100.0) / 100.0;
System.out.println( +kilograms+ " kilograms is equal to " +pounds+ " pounds");
}
else if((choice != 1) || (choice != 2)){
System.out.println("Invalid please try again");
System.out.println("Which conversion do you want?");
System.out.println("Pounds to Kilograms(enter 1)");
System.out.println("Kilograms to Pounds(enter 2)");
choice = input.nextInt();
}
}
}
}
显示菜单并询问用户他们想要转换:
您想要哪种转换?
然后询问用户应转换的重量值。
您想要转换的重量值是什么?
如果用户选择1,则将磅转换为千克,否则如果用户选择2将千克转换为磅,否则如果用户选择是其他任何内容,则告诉用户他们的答案无效并请求另一个答案。 / p>
答案 0 :(得分:1)
使用while (true)
。如果要退出循环,请设置break;
将int choice = input.nextInt();
放在循环内部的顶部,而不是放在最后。
也可以使用else
捕获所有可能的无效输入。
double kilograms, pounds;
while (true) {
System.out.println("Which conversion do you want?");
System.out.println("Pounds to Kilograms(enter 1)");
System.out.println("Kilograms to Pounds(enter 2)");
int choice = input.nextInt();
if (choice == 1) {
// okay
lbsToKg(); // TODO: implement
break; // stops the loop
} else {
// invalid, will already continue the loop
}