如何修复连续循环?

时间:2014-01-15 12:34:43

标签: java while-loop infinite-loop

我试图循环用户输入风味和勺子的数量,直到被问到“购买更多冰淇淋?”用户输入'n'但是当输入'n'时它会显示报告,然后再次询问味道?我怎么能阻止这个?

Scanner in = new Scanner(System.in);

  int index = 0;
    {
      System.out.println("What flavour was chosen (strawberry, vanilla, chocolate) or type 'end' to finish?");
      iceCreamCone[0] = in.nextLine();

      System.out.println("How many scoops of this flavour?");
      iceCreamCone[0] = in.nextLine();
      index = index + 1;

      char choice;
      System.out.println("More ice cream purchased (y/n):");
      {
        choice = in.next().charAt(0);
        while (choice == 'y') 
        {
          System.out.println("What flavour was chosen (strawberry, vanilla, chocolate) or type 'end' to finish?");
          iceCreamCone[1] = in.nextLine();
          in.nextLine();

          System.out.println("How many scoops of this flavour?");
          iceCreamCone[1] = in.nextLine();
          index = index + 1;
        }
        if (choice == 'n') {
        {
          System.out.println("Report for today: \nTotal ice cream cones sold: \nTotal sales from the customers: ");

        }
      }
    }
    }
  }

3 个答案:

答案 0 :(得分:0)

做这样的事情:

char y;

do
{


sop(which flavour);
sop(how many scoops);

System.out.println("wnat to enter more (y/n)");
Scanner sc=new Scanner(System.in); or any stream class
read(ch)
}
while(ch=='y');

答案 1 :(得分:0)

首先,你在这个程序中有两次相同的代码:

System.out.println("What flavour was chosen (strawberry, vanilla, chocolate)
or type 'end' to finish?");
  iceCreamCone[0] = in.nextLine();

  System.out.println("How many scoops of this flavour?");
  iceCreamCone[0] = in.nextLine();
  index = index + 1;

将它放在方法中并调用方法而不是调用它两次。同时将iceCreamCone[0]更改为iceCreamCone[index],这样您就不会覆盖列表中的第二个条目。

第二个问题是你的循环似乎永远不会结束。 放

System.out.println("More ice cream purchased (y/n):");
choice = in.next().charAt(0);

进入while循环结束。这样你就可以在while循环中询问是否不再购买勺子了。

答案 2 :(得分:0)

如果用户第一次要求更多的冰淇淋,你将无限循环。你告诉勺子后,你每次都要问用户。

  char choice;
  System.out.println("More ice cream purchased (y/n):");
  {
    choice = in.next().charAt(0);
    while (choice == 'y') 
    {
      System.out.println("What flavour was chosen (strawberry, vanilla, chocolate) or type 'end' to finish?");
      iceCreamCone[1] = in.nextLine();
      in.nextLine();

      System.out.println("How many scoops of this flavour?");
      iceCreamCone[1] = in.nextLine();
      index = index + 1;

      System.out.println("More ice cream purchased (y/n)");
      choice = in.next().charAt(0);
    }

      System.out.println("Report for today: \nTotal ice cream cones sold: \nTotal sales from the customers: ");

    }