Jump to content

Calculating Averages

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
chili5

chili5

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 7,247 posts
I'm making a program that inputs positive numbers from the users and calculates the average. I added a check at the beginning if the number is smaller than 0 but I'm having a problem that it won't stop and wait for an input if the number is entered less than 0.

My code is:

public class computeAverage {

	public static void main(String[] args) {

		int inputNumber; // one of the ingtegers input by the user

		int sum; // the sum  of the positive integers

		int count; // the number of positive integers

		double average; // the average of positive integers

		

		sum = 0;

		count = 0;

		

		TextIO.put("Enter your first positive integer: ");

		inputNumber = TextIO.getlnInt();

		[B]while (inputNumber <0) {

			System.out.println("\nError: Input a positive integer.");

			TextIO.put("Enter your first positive integer: ");

		}[/B]

		

		while (inputNumber != 0) {

			sum += inputNumber;

			count++;

			TextIO.put("Enter your next positive integer, or 0 to end: ");

			inputNumber = TextIO.getlnInt();

		}

		

		if (count == 0) {

			TextIO.putln("You didn't enter any data!");

		} else {

			average = ((double)sum) / count;

			TextIO.putln();

			TextIO.putln("You entered " + count + " positive integers.");

			TextIO.putln("Their average is " + average + ".");

		}

	}

}

The bold part is where my problem is. If the user enters a number such as -2 the program is to stop and ask for another number but it continues to print the two lines to the console in the while loop.

#2
2stamlers

2stamlers

    Learning Programmer

  • Members
  • PipPipPip
  • 46 posts
You need to put TextIO.getlnInt(); in the loop, to stop and wait for user input.

#3
chili5

chili5

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 7,247 posts
Thanks :D