I need help with this Java programming assignment: Declare an array to hold ten
ID: 3903130 • Letter: I
Question
I need help with this Java programming assignment:
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
import java.util.Random;
import java.util.Arrays;
public class Example {
public static void main(String[] args) {
double arr[];
arr=new double[10];
int temp[];
temp=new int[10];
for(int i=0;i<10;i++)
{
arr[i]=Math.random()*40+20;//((max-min)+1))+min
}
for (double a : arr) {
System.out.println(String.format("%.4f", a));
}
for(int i=0;i<10;i++)
{
temp[i]=(int)Math.round(arr[i]);
}
Arrays.sort(temp);
System.out.println("Here are the ints, sorted");
for(int a:temp)
System.out.print(a+" ");
}
}