gpt4 book ai didi

java - 如何在 Java 中重复 if 条件?

转载 作者:行者123 更新时间:2023-12-01 12:56:34 25 4
gpt4 key购买 nike

基本上,我希望能够输入一个不是选项的数字,然后再次提供选择的选项,并重复该语句。

Scanner keyboard = new Scanner(System.in);
double weight;
int Choice;

System.out.println("What is your weight in pounds?");
weight = keyboard.nextDouble();

System.out.println("Which planet would you like to see your weight on?\n 1. Venus 2. Mars 3. Jupiter\n 4. Saturn 5. Uranus 6. Neptune");
Choice =keyboard.nextInt();

if (Choice == 1){
System.out.println("Your weight on Venus would be " + (weight * 0.78));
}
else if (Choice == 2){
System.out.println("Your weight on Mars would be " + (weight * .39));
}
else if (Choice == 3){
System.out.println("Your weight on Jupiter would be " + (weight * 2.65));
}
else if (Choice == 4){
System.out.println("Your weight on Saturn would be " + (weight * 1.17));
}

else if (Choice == 5){
System.out.println("Your weight on Uranus would be" +(weight * 1.05));
}
else if (Choice == 6) {
System.out.println("Your weight on Neptune would be " + (weight * 1.23));
}
else
System.out.println("This was not a choice, try again!");
Choice = keyboard.nextInt();
}

最佳答案

这是一种更简单的方法,使用 do-while 循环和 switch

也固定选择

Scanner keyboard = new Scanner(System.in);
double weight;
int choice;

System.out.println("What is your weight in pounds?");
weight = keyboard.nextDouble();

do {
System.out.println("Which planet would you like to see your weight on?\n 1. Venus 2. Mars 3. Jupiter\n 4. Saturn 5. Uranus 6. Neptune\n 7. Exit");
choice = keyboard.nextInt();
switch(choice) {
case 1:
System.out.println("Your weight on Venus would be " + (weight * 0.78));
break;
case 2:
System.out.println("Your weight on Mars would be " + (weight * .39));
break;
case 3:
System.out.println("Your weight on Jupiter would be " + (weight * 2.65));
break;
case 4:
System.out.println("Your weight on Saturn would be " + (weight * 1.17));
break;
case 5:
System.out.println("Your weight on Uranus would be" +(weight * 1.05));
break;
case 6:
System.out.println("Your weight on Neptune would be " + (weight * 1.23));
break;
case 7:
System.out.println("Bye");
break;
default:
System.out.println("This was not a choice, try again!");
break;
}
} while (choice != 7);

关于java - 如何在 Java 中重复 if 条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23836980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com