2014-04-04 47 views
-2

我需要幫助,瞭解如何向我的代碼中添加一個變量,以輸出報告中接受調查的人數。使用一個名爲personCount的新變量來做到這一點,每次運行循環時都應該更新它。添加一個變量,每次運行循環時都應該更新Java

我試過這種方式,但在開始循環寫

int count=0; 

之前和內環路寫

count++; 

此計數變數將存放它不工作

class morecoffee 
{ 
    public static void main (String [] args) 
    { 
     Scanner input = new Scanner(System.in); 

     int person, preference, nothing, sugar, sweetener, count, quit, personcount; 

     nothing = sugar = sweetener = 0; 
     int personcount=0;  
     for (;;) 
    { 

     System.out.println ("How do you sweeten your coffee?"); 
     System.out.println ("1. I don't"); 
     System.out.println ("2. With sugar?"); 
     System.out.println ("3. With sweetener?"); 
     System.out.println ("4. Quit"); 
     System.out.println (personcount + " people took the survey "); 

     personcount++; 
     preference = input.nextInt(); 


     if (preference == 1) 
       nothing++; 

      else if (preference == 2) 
        sugar++; 
      else if (preference == 3) 
       sweetener++; 

    if (preference == 4) 
     break; 
    } 
     System.out.println ("Survey Report"); 
     System.out.println ("============="); 

     System.out.println (nothing + " person don't sweeten coffee"); 
     System.out.println (sugar + " person use sugar in coffee"); 
     System.out.println (sweetener + " person use sweetener in coffee"); 
    } 
} 
+1

你試過了什麼?爲什麼沒有工作?只是問堆棧溢出不會幫助你成爲一個更好的程序員。 – RyanS

+0

只需複製變量'sweetener'的變量,唯一的區別是什麼時候對它做'++' –

+1

嗯,你知道每個人都沒有說什麼,糖或者甜味劑,所以你可以結合這些值。或者你可以跟蹤計數,每次你經過循環而沒有突破時遞增。 – thegrinner

回答

1

所需值。在迴路後打印

System.out.println(count); 
+0

我編輯了像你說的代碼,但它不會創建一個類,它會給出一個錯誤。無=糖=甜味劑= 0; int personcount = 0; \t \t \t \t爲(;;){ 的System.out.println( 「你怎麼甜的咖啡?」); System.out.println(「1.我不」); System.out.println(「2. With sugar?」); System.out.println(「2. With sugar?」); System.out.println(「3. With sweetener?」); System.out.println(「4. Quit」); System.out.println(personcount +「people took the survey」); \t \t personcount ++; preference = input.nextInt(); – user3499202

+0

@ user3499202你得到了什麼錯誤? – maxx777

+0

@ user3499202並嘗試格式化您的意見作爲weel – maxx777

相關問題