猿问

试图检查用户输入到我的数组

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


慕尼黑的夜晚无繁华
浏览 141回答 1
1回答

繁星coding

您必须使用来检查数组的每个索引flavors。(可能应该重命名为userFlavor)。String[] chooseFlavors = {"plain", "strawberry", "raspberry", "caramel", "chocolate"};...&nbsp;boolean flavorFound = false;while (!flavorFound) { // Loop until flavorFound is true&nbsp; System.out.println("Please choose flavor:");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; userFlavor = scnr.nextLine();&nbsp; for(int i = 0; i < chooseFlavors.length; i++) { // Loop from 0 to choosFlavors.length&nbsp; &nbsp; &nbsp; if(userFlavor.equals(chooseFlavors[i]) { // Compare user input to flavor at index i&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(userFlavor + " found at index " + i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; flavorFound = true; // This is the flag to break out of while loop&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break; // Only breaks out of for loop&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Please choose from flavors above.");&nbsp; &nbsp; &nbsp; }&nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答