2014-01-15 59 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: "); 

    }