2014-01-15 56 views
0

我想循环用户输入的味道和勺的数量,直到当问'购买更多的冰淇淋?用户输入'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: "); 

     } 
     } 
    } 
    } 
    } 
+8

你可以使用“休息”摆脱循环..但你的循环在哪里? – TheLostMind

+0

使用一个简单的'while(expression == true)'循环。 – Tdorno

+4

解析发布代码:哔声:错误:部分代码丢失 –

回答

0

做这样的事情:

焦炭ÿ;

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'); 
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循环中询问是否购买了更多的勺子。

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: "); 

    }