简体   繁体   中英

Java - How to only count the inputted positive numbers

I am trying to find sum and averags of user inputed numbers and i also Need my program to only sum the positive numbers entered. It needs to calculate only the positive numbers sum and ignore the negative inputs, would i put my num=0 or not?

import java.util.Scanner;

public class J12ForSumPos {
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);

        int maxNumbers, i, num, average;
        int sum = 0;
        System.out.print("Enter Max Numbers: ");
        maxNumbers = console.nextInt();
        System.out.println();

        for (i = 1; i <= maxNumbers; i = i + 1) {
            System.out.print("Enter Value " + i + ": ");
            num = console.nextInt();
            sum = sum + num;
        }
        average = sum / maxNumbers;

        if (sum >= 0) {
            System.out.println();
            System.out.println("Sum: " + sum);
            System.out.println();
            System.out.println("Average: " + average);
            System.out.println();
        } else {
            System.out.println("Sum is: " + sum * 0);
            System.out.println();
            System.out.println("Cannot Calculate Average - no positives entered");
        }
    }
}

You can try something like this:

Scanner console = new Scanner(System.in);

int maxNumbers = 0;
int totalSum = 0; // Sum of all numbers (positive and negative)
int totalAverage = 0; // Average of all numbers (positive and negative)
int positiveSum = 0; // Sum of all positive numbers
int positiveAverage = 0; // Average of all positive numbers
int positiveNumberCount = 0; // Amount of positive numbers entered

System.out.print("Enter Max Numbers: ");
maxNumbers = console.nextInt();
System.out.println();

for(int i=1; i<=maxNumbers; i=i+1)
{
    System.out.print("Enter Value " + i + ": ");
    int num = console.nextInt();

    if(num >= 0) {
      positiveSum = positiveSum + num;
      positiveNumberCount = positiveNumberCount + 1;
    }

    totalSum = totalSum + num;
}

positiveAverage = positiveSum / positiveNumberCount;
totalAverage = totalSum / maxNumbers;

It's up to you to decide whether or not to include 0 as a positive or a negative number, or exclude it. In my example it's being treated as a positive number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM