( Count of positive, negative, and zero values )Write a program to enter the numbers till the user wants and at the end it should display the count of positive, negative and zeros entered.

here is a Java program that allows the user to enter numbers until they choose to stop, and then displays the count of positive numbers, negative numbers, and zeros entered.

Count of positive, negative, and zero values

				
					import java.util.Scanner;

public class NumberCounter {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int positiveCount = 0, negativeCount = 0, zeroCount = 0;
        char choice;

        do {
            System.out.print("Enter a number: ");
            int num = scanner.nextInt();

            if (num > 0) {
                positiveCount++;
            } else if (num < 0) {
                negativeCount++;
            } else {
                zeroCount++;
            }

            System.out.print("Do you want to enter another number? (y/n): ");
            choice = scanner.next().charAt(0);
        } while (choice == 'y' || choice == 'Y');

        System.out.println("\nCount of positive numbers: " + positiveCount);
        System.out.println("Count of negative numbers: " + negativeCount);
        System.out.println("Count of zeros: " + zeroCount);

        scanner.close();
    }
}

				
			

Explanation:

  1. Import Statement:

    • import java.util.Scanner; is used to include the Scanner class for user input.
  2. Variable Declaration:

    • positiveCount, negativeCount, zeroCount: Counters for positive numbers, negative numbers, and zeros respectively.
    • choice: Stores the user’s decision to continue entering numbers or not.
  3. Input Loop:

    • The do-while loop allows the user to enter numbers until they choose to stop.
    • After entering a number, the program checks if the number is positive, negative, or zero and increments the respective counter.
    • The user is then prompted to enter another number or stop. If they enter ‘y’ or ‘Y’, the loop continues.
  4. Output:

    • After the loop exits, the program prints the counts of positive numbers, negative numbers, and zeros.

Sample Output:

				
					Enter a number: 5
Do you want to enter another number? (y/n): y
Enter a number: -3
Do you want to enter another number? (y/n): y
Enter a number: 0
Do you want to enter another number? (y/n): y
Enter a number: 2
Do you want to enter another number? (y/n): n

Count of positive numbers: 2
Count of negative numbers: 1
Count of zeros: 1

				
			
prime number

To run this program, save it in a file named NumberCounter.java, compile it using javac NumberCounter.java, and run it using java NumberCounter. The program will prompt you to enter numbers and then display the counts as described.

Scroll to Top