因此,用户必须在 1 到 3 之间选择一个数字。否则,他们会被告知重试。如果用户尝试一个小于 1 或大于 3 的数字,他们选择的任何数字都会存储在“选择”变量中,并导致程序在应该停止时继续运行。我以为会有一个简单的解决方案,但显然这超出了我作为初学者的范围。对我来说显而易见的事情是以某种方式清除或清空在用户输入不成功后分配给“选择”的值。这可能吗?
import java.util.Scanner;
public class Furniture2Test {
public static void main(String[] args) {
wood();
} // end main
public static void wood() {
int choice;
int pine = 1;
int oak = 2;
int mahogany = 3;
int pineCost = 100;
int oakCost = 225;
int mahoganyCost = 310;
Scanner keyboard = new Scanner(System.in);
System.out.println("What type of table would you like?");
System.out.println("1. pine");
System.out.println("2. oak");
System.out.println("3. mahogany");
choice = keyboard.nextInt();
if (choice == 1) {
choice = pineCost;
} else if (choice == 2) {
choice = oakCost;
} else if (choice == 3) {
choice = mahoganyCost;
} else if (choice > 3 || choice < 1) {
System.out.println("Try again.");
choice = -1;
wood();
}
System.out.println("That will be $" + choice + ".");
size(choice);
} // end wood
public static void size(int choice) {
int sizeChoice;
int large = 35;
Scanner keyboard = new Scanner(System.in);
System.out.println("What size will that be?");
System.out.println("1. large");
System.out.println("2. small");
sizeChoice = keyboard.nextInt();
if (sizeChoice == 1)
System.out.println("That will be $" + (choice + large) + ".");
else if (sizeChoice == 2)
System.out.println("That will be $" + choice);
else
System.out.println("Please, enter either a 1 or a 2.");
} // end size
}
最佳答案
您的要求可以通过 do...while 循环轻松完成。示例代码如下:
do{
System.out.println("Choose option between 1 and 3");
choice = keyboard.nextInt();
}while(!(choice > 3 || choice < 1));
if (choice == 1) {
choice = pineCost;
} else if (choice == 2) {
choice = oakCost;
} else if (choice == 3) {
choice = mahoganyCost;
}
希望这对您有所帮助。
关于java - 如何不断要求用户选择有效选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19016090/