为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕尼黑的夜晚无繁华 2021-04-28 13:46:00
我对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.");
查看完整描述

1 回答

?
繁星coding

TA贡献1797条经验 获得超4个赞

您必须使用来检查数组的每个索引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.");

      }

  }


}


查看完整回答
反对 回复 2021-05-19
  • 1 回答
  • 0 关注
  • 123 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信