I need help with this Java programming assignment (make sure to meet all the req
ID: 3909765 • Letter: I
Question
I need help with this Java programming assignment (make sure to meet all the requirements):
Declare an array to hold ten doubles. Use a for loop to add ten random doubles, all in the range from 20.0 to 60.0, inclusive, to this array. Use a foreach loop to print all elements of the array accurate to four decimal places, one element per line. Pass the array of doubles to a method that executes as follows:
uses a for loop and a Math class method to round up each element to its nearest integer.
creates a 10-element array of ints named temp.
uses another for loop to cast each element of the double array to temp.
returns temp
Back in main, use the Arrays class to sort the array returned by the method and then use a foreach loop to print all elements on one line, separated by spaces. See Sample Output below.
Sample Output
Here are the doubles
36.0481
36.2494
57.5059
25.7974
30.0139
45.0493
27.1609
49.2794
43.2146
29.9653
Here are the ints, sorted
26 28 30 31 37 37 44 46 50 58
Explanation / Answer
Java program:
import java.util.Arrays;
public class TestApp
{
//main method
public static void main(String[] args)
{
//array to hold 10 doubles
double [] array = new double[10];
//min and max variables to specify range
double min=20.0;
double max=60.0;
//for loop to add ten random doubles
for(int i=0;i<array.length;i++)
{
//generating ten random doubles using min and max variables
double x = (Math.random()*((max-min)+1))+min;
//adding ten random doubles to array
array[i]=x;
}
System.out.println("Here are the doubles");
/*foreach loop to print all elements of the array
accurate to four decimal places,
one element per line.*/
for(double e:array)
{
System.out.printf("%.4f ",e);
}
//passing the array of doubles to a method
int a[]=method(array);
//use the Arrays class to sort the array returned by the method
Arrays.sort(a);
System.out.println(" Here are the ints, sorted");
/*foreach loop to print all elements on one line, separated by spaces.*/
for(int i:a)
{
System.out.print(i+" ");
}
}
public static int[] method(double ar[])
{
/*for loop and a Math class method to round up
each element to its nearest integer.*/
for(int i=0;i<ar.length;i++)
{
//Math.round() method to round up each element to its nearest int
ar[i]=Math.round(ar[i]);
}
//creates a 10-element array of ints named temp.
int temp[]=new int[10];
//uses another for loop to cast each element of the double array to temp.
for(int i=0;i<temp.length;i++)
{
temp[i]=(int)ar[i];
}
return temp;
}
}
Output:
Here are the doubles
38.3137
41.7856
25.9686
44.7604
45.0960
41.6203
29.9637
59.9821
25.7913
36.6623
Here are the ints, sorted
26 26 30 37 38 42 42 45 45 60