2014-04-04 23 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

相关问题