Write a program to count of positive, negative and zeros


The program prompts the user to enter a number and keeps a count of the positive, negative, and zero numbers entered until the user chooses to stop. At the end, the program prints out the count of each category of numbers.

  • Import the Scanner class from the java.util package.
  • Define a class named "Count_PosNegZero".
  • Define the main() method within the class.
  • Create a new instance of the Scanner class to read user input.
  • Declare and initialize variables to keep track of the count of positive, negative, and zero numbers entered by the user.
  • Declare a character variable "choice" to store the user's choice of continuing or not.
  • Start a do-while loop to repeatedly ask the user to enter a number and count the number of positive, negative, and zero numbers.
  • Inside the do-while loop, prompt the user to enter a number and store it in the "number" variable.
  • Check if the number is positive, negative, or zero and increment the respective count variables.
  • Ask the user if they want to continue or not and store their choice in the "choice" variable.
  • Continue the loop if the user chooses to continue.
  • Outside the loop, print the count of positive, negative, and zero numbers entered by the user.
  • End the main method and the class.

Source Code

import java.util.Scanner;
class Count_PosNegZero
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);       
        int c_pos = 0,c_neg = 0,c_zero = 0;
		char choice;	
        do
        {
            System.out.print("Enter the number ");
            int number = input.nextInt();
 
            if(number > 0)
            {
                c_pos++;
            }
            else if(number < 0)
            {
                c_neg++;
            }
            else
            {
                c_zero++;
            }
 
            System.out.print("Do you want to Continue y/n? ");
            choice = input.next().charAt(0);
 
        }while(choice=='y' || choice == 'Y');
 
        System.out.println("Positive numbers: " + c_pos);
        System.out.println("Negative numbers: " + c_neg);
        System.out.println("Zero numbers: " + c_zero);
    }  
}

Output

Enter the number 23
Do you want to Continue y/n? y
Enter the number -34
Do you want to Continue y/n? y
Enter the number 0
Do you want to Continue y/n? y
Enter the number 43
Do you want to Continue y/n? y
Enter the number -3
Do you want to Continue y/n? y
Enter the number -45
Do you want to Continue y/n? n
Positive numbers: 2
Negative numbers: 3
Zero numbers: 1

Example Programs