尝试检查用户对我的数组的输入



我对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.");

您必须使用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.");
}
}
}

相关内容

  • 没有找到相关文章

最新更新