在java中停止循环

时间:2012-07-31 03:22:52

标签: java

  

可能重复:
  Taking average of user input number

for (int n1 = in.nextInt(); n1 >= 0; n1 = in.nextInt())
  {
          int total = 0;
          int count = 0;

          while (n1 >= 0)
          {
                  n1 = in.nextInt();
                  total = total + n1;
                  count = count + 1;

          }
          out.println(total);
          out.println(count);
  } 

我希望我输入的所有数字都加起来,这段代码是否正确?它只添加了我最后的2个输入。我希望循环继续运行,直到用户输入负数,然后循环停止然后输出我的总数和计数。

Scanner in = new Scanner(System.in);
Printstream out = System.out;

2 个答案:

答案 0 :(得分:2)

int total = 0;
int count = 0;

while (true) {
    int n = in.nextInt();
    if (n < 0) 
        break;
    total += n;
    count ++;
}
out.println(total);
out.println(count);

答案 1 :(得分:0)

您的代码应如下所示。

int total = 0;
int count = 0;
int n1;

try
{
    while((n1=Integer.parseInt(in.nextLine()))>=0)
    {
        total = total + n1;
        count = count + 1;
    }
}
catch(Exception e)
{
    System.out.println(e.toString());
}

out.println("Total     = "+total);
out.println("Count     = "+count);

Format df=new DecimalFormat("#.##");
out.println("Average   = "+df.format((double)total/count));