检查列表中有多少是正数

时间:2014-10-12 21:17:26

标签: java string loops

编写一个名为PositiveNegative的程序,读取未指定数量的整数,确定输入了多少正值和负值,并计算输入值的总和和平均值(不计算零)。当用户输入0(零)时,输入的读取结束。显示正负输入的数量,总和和平均值。应将平均值计算为浮点数。设计程序,以便它询问用户是否希望在每组条目后继续输入新的输入,只有当他们没有用“是”回答问题时结束程序。

以下是一个示例运行:

Input a list of integers (end with 0): 1   2   -1   3   0

# of positive inputs:   3
# of negative inputs:   1
The total:              5.0
The average:            1.25

Would you like to continue with new inputs? yes
Input a list of integers (end with 0): 0

No numbers were entered except 0

Would you like to continue with new inputs? no

这是我的代码:

import java.util.*;

public class PositiveNegative
{
  public static void main(String[] args){

      Scanner input = new Scanner(System.in);
      String answer;
      int countpositive = 0;
      int countnegative = 0;
      int total = 0;
      int num = 0;

      System.out.print("Input a list of integers (end with 0): ");

      do{
         String list = input.nextLine();

         for(int i = 0; ; i=i+2 ){
            num = Integer.parseInt(list.substring(i,i+1));

            if( num == 0)
               break;
            else if ( num > 0)
               countpositive++;
            else if ( num < 0)
               countnegative--;
            total = total + num;
            }
            double average = total/(countpositive + countnegative); 
            System.out.println("# of positive inputs: "+countpositive);
            System.out.println("# of negative inputs: "+countnegative);
            System.out.println("The total: "+total);
            System.out.println("The average"+average);
            System.out.println("\n ");
            System.out.print("Would you like to continue with new inputs? ");
            answer = input.next();

         }while(answer.equalsIgnoreCase("Yes"));

       }
   }  

我可以编译文件,但是当我运行它时,我无法得到样本运行的结果。

1 个答案:

答案 0 :(得分:1)

当遇到负整数时,您递减countnegative--;)负整数计数而不是递增它(countnegative++;)。