Object-Oriented Programming with Java, part II – Exercise 2

Write a number that asks user for input until the user inputs 0. After this, the program prints the average of the positive numbers (numbers that are greater than zero).

My Code

Main

import java.util.Scanner;

public class AverageOfPositiveNumbers {

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

        int i = 0;
        int total = 0;
        while (true) {
            int input = scanner.nextInt();
            if (input == 0) {
                break;
            }
            if (input > 0) {
                total += input;
                i++;
            }
        }
        if (total == 0) {
            System.out.println("Cannot calculate the average");
        } else {
            System.out.println((double) total / i);
        }

    }
}

Model Code

Main

import java.util.Scanner;

 

public class AverageOfPositiveNumbers {

 

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

 

        int count = 0;

        int sum = 0;

        while (true) {

            int number = Integer.valueOf(scanner.nextLine());

 

            if (number == 0) {

                break;

            }

 

            if (number < 0) {

                continue;

            }

 

            count = count + 1;

            sum = sum + number;

        }

 

        if (count == 0) {

            System.out.println("Cannot calculate the average");

        } else {

            System.out.println(1.0 * sum / count);

        }

    }

}

Comments

Fairly much the same.

Leave a comment