Q:

Write a Java program that will read an unspecified number of integers and then print number of positives, number of negatives, their count, sum and average. Your program should stop reading numbers when the user enter 0. Name your class CountPosNeg

0

Write a Java program that will read an unspecified number of integers and then print number of positives, number of negatives, their count, sum and average. Your program should stop reading numbers when the user enter 0. Name your class CountPosNeg

 

Sample run 1

Enter integers ending with 0: 1 2 -1 3 0

The number of positives is 3 The number of negatives is 1 The count is 4 The sum is 5 The average is 1.25

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

import java.util.Scanner;

public class Lab5 {
    public static void main(String[] args) {
    Scanner input=new Scanner(System.in);
     System.out.print("Enter integers ending with 0 :");
     int x,countPositives=0,countNegatives=0,count=0,sum=0;
     double average;
     do{
         x=input.nextInt();
         if(x==0)
             continue;
         sum=sum+x;
         count=count+1;
         if(x>0)
             countPositives++;
         else if(x<0)
             countNegatives++;
     }
     while(x!=0);    
     System.out.println("The number of positives is "+countPositives);
     System.out.println("The number of negatives is "+countNegatives);
     System.out.println("The count is "+count);
     System.out.println("The sum is "+sum);
     System.out.println("The average is "+((double)sum/count));  
    }
}

need an explanation for this answer? contact us directly to get an explanation for this answer
need an explanation for this answer? contact us directly to get an explanation for this answer

import java.util.Scanner;

public class CountPosNeg {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int x, pos=0, neg=0, sum = 0, count=0;
double avg;
System.out.print("Enter integers ending with 0: ");
x=kb.nextInt();
while (x!=0) {
count++;
sum+=x;
if (x>=0) pos++; else neg++;
x = kb.nextInt();
}
avg = (double) sum / count;
System.out.println("The number of positives is "+pos);
System.out.println("The number of negativess is "+neg);
System.out.println("The count "+count);
System.out.println("The sum "+sum);
System.out.println("The average "+avg);
kb.close();
}
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (2)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now