Monday 12 June 2017

Java Code to count Negative and Positive Numbers in a set

Problem:

Design an algorithm that reads a list of numbers and makes a count of the number of negatives and the number of non-negative members in the set.

Algorithm:

1. Prompt then read the number of elements in the list.
2. Initialize both positive and negative counters to zero.
3. while there are still numbers to be processed repeatedly do
    a. Check the number is greater than zero. If it is then increment the positive number counter to one.
    b. Check the number is less than zero. If it is then increment the negative number counter to one.
4. Print both counters.

Solution:

package com.myprograms;

import java.util.Scanner;

public class CountOfNegativeAndPositive {

static int a[];
static int positiveNo = 0;
static int negativeNo = 0;
static Scanner s;

public CountOfNegativeAndPositive(int n) {
a = new int[n];
}

private void getTheNumbers(){

for(int i = 0; i<a.length; i++){
System.out.println("enter number :" + i);
a[i] = s.nextInt();
}
}

private void countPositiveAndNegative(){
for(int i = 0; i< a.length; i++){
if(a[i] > 0){
positiveNo = positiveNo + 1;
}
else if(a[i] < 0){
negativeNo = negativeNo + 1;
}
}
}

public static void main(String[] args) {
s = new Scanner(System.in);
System.out.println("How many numbers you want to hold in the set");
CountOfNegativeAndPositive countOfNegativeAndPositive = new CountOfNegativeAndPositive(s.nextInt());
countOfNegativeAndPositive.getTheNumbers();
countOfNegativeAndPositive.countPositiveAndNegative();
System.out.println("The Number of positive numbers entered: " + positiveNo);
System.out.println("The Number of negative numbers entered: " + negativeNo);

s.close();
}
}

OutPut:

How many numbers you want to hold in the set
3
enter number :0
-1
enter number :1
0
enter number :2
1
The Number of positive numbers entered: 1
The Number of negative numbers entered: 1

  

No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...