我对Java完全陌生,我正在尝试获取用户输入以检查数组中的有效输入,并继续执行代码,如果在获得有效输入之前重复该操作无效,那么
public class Cheesecake {
public static void main(String[] args) {
// TODO Auto-generated method stub
float biteSize = 3;
float small = 9;
float large = 12;
String chosenSize;
double pricePerInch = 0;
double total = 0;
String[] chooseSizes = {"bite size", "small", "large"};
String[] chooseFlavors = {"plain", "strawberry", "raspberry", "caramel", "chocolate"} ;
Scanner scnr = new Scanner(System.in);
System.out.println("Flavors to choose from: plain, strawberry, raspberry, caramel, chocolate."); //giving user flavor list
/*System.out.println("Please choose flavor:");
flavors = scnr.nextLine();*/
String flavors;
while (true) {
System.out.println("Please choose flavor:");
flavors = scnr.nextLine();
if (flavors.equals(chooseFlavors))
break;
else
System.out.println("Please choose from flavors above.");
答案 0 :(得分:1)
您必须使用flavors
检查数组的每个索引。 (可能应该重命名为userFlavor
)。
String[] chooseFlavors = {"plain", "strawberry", "raspberry", "caramel", "chocolate"};
...
boolean flavorFound = false;
while (!flavorFound) { // Loop until flavorFound is true
System.out.println("Please choose flavor:");
userFlavor = scnr.nextLine();
for(int i = 0; i < chooseFlavors.length; i++) { // Loop from 0 to choosFlavors.length
if(userFlavor.equals(chooseFlavors[i]) { // Compare user input to flavor at index i
System.out.println(userFlavor + " found at index " + i);
flavorFound = true; // This is the flag to break out of while loop
break; // Only breaks out of for loop
} else {
System.out.println("Please choose from flavors above.");
}
}
}