Count positive and negative numbers and compute the average of the numbers.
import java.util.Scanner;
public class PositiveNegative
{
public static void main(String[] args)
{
int pos = 0, neg = 0;
int numbers, close;
double total= 0;
boolean zero = true;
// create scanner and ask for integers
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer, the input ends if it is 0: ");
//do while loop for ending program
do
{
//do while loop to process input
do
{
//input integers
numbers = input.nextInt();
//if integer is zero, set zero to false and end this run
if (numbers == 0)
zero = false;
//determines if positive and counts
else if (numbers > 0)
{
pos++;
total = total + numbers;
}
//determines if negative and counts
else
{
neg++;
total = total + numbers;
}
}
//if number is not zero, keeps looping, ends if zero
while (numbers != 0);
//prints results
if (total != 0)
{
System.out.println("The number of positives is " + pos);
System.out.println("The number of negatives is " + neg);
System.out.println("The total is " + total);
System.out.println("The average is " + (total / (neg + pos)));
}
//if only number is zero prints
else
{
System.out.print("No numbers are entered except 0.");
}
//Continues or stops main do while loop
System.out.println("Do you want to continue? (0 to stop)");
close = input.nextInt();
}
while(close != 0);
}
}
No comments:
Post a Comment