In: Computer Science
[15 marks] (GetPositiveNumbers.java) Write a method that receives an array of integers as a parameter. The method finds and returns an array which contains the positive numbers. For example, if the method receives an array with the following elements: 0 3 -1 2 5 1 -5 2 -2 0 the method should return an array with the following elements: 3 2 5 1 2 In the main method, randomly generate an array of 10 random integers between -5 and 5, inclusive, invoke the method, and display the returned array. java program
JAVA PROGRAM
import java.util.*;
import java.util.Random;
public class Main
{
public static int[] fun(int arr[])
{
int j=0;
// runs the loop to find how many positive numers are there in
array
for(int i =0;i<10;i++){
if(arr[i]>=0){
j++;
}
}
// declaration of array only how many positive numbers are
there
int arr2[] = new int[j];
int k =0;
// runs the loop
for(int i =0;i<j;i++)
{
// condition finds the positive number
if(arr[i]>=0)
{
arr2[k] = arr[i];
k++;
}
}
// returning only positive numbers array
return arr2;
}
//main function
public static void main(String[] args)
{
Random rand = new Random();
// array declaration
int arr[] = new int[10];
int random_int ;
//runs the loop
for(int i=0;i<10;i++)
{
// Generates the random number from -5 to 5
inclusive
arr[i] = (int)(Math.random() * (6 - (-5) + 1) +
(-5));
}
//calling a function & passing the parameter,
returned value is stored in arr3[] array
int arr3[] = fun(arr);
//printing the returned value only positive
numbers
for(int i=0;i<arr3.length;i++){
System.out.print(arr3[i]+" ");
}
}
}
OUTPUT
THUMBS UP