0

The below problem comes from Chapter 5 of the book Intro to Java by Daniel Liang:

(Count positive and negative numbers and compute the average of numbers) Write a program that reads an unspecified number of integers, determines how many positive and negative values have been read, and computes the total and average of the input values (not counting zeros). Your program ends with the input 0. Display the average as a floating-point number.

Here is a sample run:
Enter an integer, the input ends if it is 0: 1 2 -1 3 0
The number of positives is 3
The number of negatives is 1
The total is 5.0
The average is 1.25

Enter an integer, the input ends if it is 0: 0
No numbers are entered except 0

My code currently fulfills the requirements of the question but I'd like to cover all of my bases. With a very basic knowledge of Java, is there a way I can check the nextInt in my while statement to see if:

  1. The number series doesn't end with a 0. In my testing, the program just seems to stop (note my debugging output in my While statement). I am guessing there isn't a simple way to do this, thus we are to use 0 as a sentinel, but I figured I would ask.

  2. If only the Enter key is pressed. When I do that in NetBeans the prompt moves to the next line, I would like to include a message notifying the user that nothing was entered and to enter an integer.

My Code:

    /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package positivenegative;

/**
 *
 * @author
 */
import java.util.Scanner;

public class PositiveNegative {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Scanner input = new Scanner(System.in);

        // Welcome message
        System.out.println("Welcome to the Number Averagererer.");
            // Yes I'm aware "Averagererer" isn't a word
        System.out.println("Be sure to enter a 0 at the end");
        System.out.println("or the program will not work.");
        System.out.print("Enter an integer, the input ends if it is 0: ");

        // Initialize variables
        int number, totalPositive=0, totalNegative=0, counter=0;  
        double average=0;

        // Process the entered variables and sort/calculate them        
        while ((number = input.nextInt()) != 0){ // Continues if number isn't 0
            System.out.println(number); //debugging to see what the nextInt is doing
            // Adds to positive  
            if (number > 0){
                totalPositive++;
                counter++;
                average = (average + number);         
                }
            // Adds to negative
            else{
                System.out.println(number);
                totalNegative++;
                counter++;        
                average = (average + number);
                }
        }

    // Output message if the user only enters "0"
    if (counter == 0){
        System.out.println("No numbers were entered except 0");
        }                    

    // Output message with calculated data from input
    else{
        double total = average;
        average = (average / counter);
        System.out.println("The number of positives is: " + totalPositive);
        System.out.println("The number of negatives is: " + totalNegative);
        System.out.println("The total is: " + total);
        System.out.println("The average is: " + average);
        }
    }
}
CubeJockey
  • 2,209
  • 8
  • 24
  • 31
  • I do not really understand what you are asking for. Part A: Do you want your app to accept 0 as an input? Part B: Do you want your app to accept any character for input? – Travis Pettry Sep 02 '15 at 13:48

1 Answers1

1

Something like this should work:

package positivenegative;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class PositiveNegative
{
    public static void main(final String[] args)
    {
        // Welcome message
        System.out.println("Welcome to the Number Averagererer.");
        // Yes I'm aware "Averagererer" isn't a word
        System.out.println("Be sure to enter a 0 at the end");
        System.out.println("or the program will not work.");
        System.out.print("Enter an integer, the input ends if it is 0: ");

        // Initialize variables
        int number = -1;
        int totalPositive = 0;
        int totalNegative = 0;
        int counter = 0;
        double average = 0;
        String line = "";
        while (line.isEmpty())
        {
            line = readLine();
            if (line.isEmpty())
            {
                System.out.println("Line is empty. Enter number!");
            }
        }

        try (final Scanner input = new Scanner(line))
        {
            // Process the entered line and sort/calculate them
            while (input.hasNextInt())
            {
                number = input.nextInt();
                if (number == 0)
                {
                    // stop if number is 0
                    break;
                }
                System.out.println("number: " + number);// TODO: remove
                // Adds to positive
                if (number > 0)
                {
                    totalPositive++;
                }
                // Adds to negative
                else
                {
                    totalNegative++;
                }
                counter++;
                average = (average + number);
            }

            // Output message if the user only enters "0"
            if (counter == 0)
            {
                System.out.println("No numbers were entered except 0");
            }

            // Output message with calculated data from input
            else
            {
                final double total = average;
                average = (average / counter);
                System.out.println("The number of positives is: " + totalPositive);
                System.out.println("The number of negatives is: " + totalNegative);
                System.out.println("The total is: " + total);
                System.out.println("The average is: " + average);
            }
        }
    }

    private static String readLine()
    {
        try
        {
            final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            final String s = br.readLine();
            return s;
        } catch (final IOException e)
        {
            e.printStackTrace();
            return "";
        }
    }
}

With your scanner, you could use input.hasNextInt() to test if there are more numbers, but it will block until there are. More details on the blocking can be found here.

Community
  • 1
  • 1
Burkhard
  • 14,596
  • 22
  • 87
  • 108