JAVA Programming (Count postive and negative numbers and compute the average of
ID: 656138 • Letter: J
Question
JAVA Programming
(Count postive and negative numbers and compute the average of the numbers)
Write a program that reads and unspecified number of integers, determines how many negative and postive values have been read, and computes the total and average of the input values (not counting zeros). Your program ends with the input 0. Display the average as a floating-point number.
That is the problem....Then it gives a sample run.....
Enter an integer, the input ends if it is 0: 1 2 -1 3 0
The number of postives is 3
The number of negatives is 1
The total is 5
The average is 1.25
Enter an integer, the input ends if it is 0: 0
No numbers are entered except 0
Explanation / Answer
public class Numbers {
public int i=0;
public int arr[];
public int getvalues()
{
Scanner sc=new Scanner(System.in);
System.out.println("enter the number of elements:");
int num=sc.nextInt();
System.out.println("Enter an integer, the input ends if it is 0:");
for(i=0;i<num;i++)
{
arr[i]=sc.nextInt();
if(arr[i]==0)
{ System.out.println("No numbers are entered except 0.");
System.exit(1);
}
}
return arr[i];
}
public void calculate(int arr[])
{
int sum=0;
int i=0;
int avg=0;
int countp=0, countn=0;
for( i=0;i<=arr.length;i++)
{
if(arr[i]>0)
countp++;
else countn++;
}
System.out.println("The number of positives is :"+countp);
System.out.println("The number of negatives is :"+countn);
System.out.println("Total is :"+arr.length);
while(i!=arr.length)
{
sum=sum+arr[i];
avg=sum/arr.length;
i++;
}
System.out.println("The average is:"+avg);
}
public static void main(String[] args)
{
Numbers n=new Numbers();
n.getvalues();
n.calculate(n.arr);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.