计算正数和负数

时间:2014-09-18 15:31:35

标签: java

public class Exercise_442 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    int count=0;
    int positive=0;
    int negative =0;
    int nums=0;
    int sum=0;

    Scanner keyboard = new Scanner(System.in);
    System.out.println("Pleaes enter a positive or negative integer");
    nums = keyboard.nextInt();


    while(nums!=0){
        sum+=nums;
        System.out.println("Plese enter a positive or negative integer");
        nums = keyboard.nextInt();

        if(nums<0)
            negative++;

         if (nums>0)
            positive++;

    }
    System.out.println("The sum of these numbers is " +sum);
     System.out.println("The amount of negative numbers here is " + negative);
      System.out.println("The amount of positive numbers here is " + positive);
    }
  }

当我输入时,我需要计算正数和负数。它会在用户输入0时显示这些数据。它会对负数进行计数并获得总和,但是当计算正整数时,我不知道它为什么会缺少一个数字?

1 个答案:

答案 0 :(得分:2)

第一次进入while循环时,+ / - 会忽略您的第一个nums。

我们假设您输入1为nums。它会在总和中加1,然后在不评估&gt;的情况下请求新输入。或者&lt;。

将if语句移到while循环中的nums = keyboard.nextInt();之上。

    while(nums!=0){
        sum+=nums;

        //moved everything up before we pull nextInt
        if(nums<0)
            negative++;

         if (nums>0)
            positive++;

        System.out.println("Plese enter a positive or negative integer");
        nums = keyboard.nextInt();

    }