我需要幫助,瞭解如何向我的代碼中添加一個變量,以輸出報告中接受調查的人數。使用一個名爲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");
}
}
你試過了什麼?爲什麼沒有工作?只是問堆棧溢出不會幫助你成爲一個更好的程序員。 – RyanS
只需複製變量'sweetener'的變量,唯一的區別是什麼時候對它做'++' –
嗯,你知道每個人都沒有說什麼,糖或者甜味劑,所以你可以結合這些值。或者你可以跟蹤計數,每次你經過循環而沒有突破時遞增。 – thegrinner