Write a program with the following methods in java A method
Write a program with the following methods (in java)
A method which takes one integer parameter n which will be the size of an array. Using the parameter initialize an array of size n with random integer numbers between 1 and 20. This method should return the randomly generated array.
A method which takes one integer array parameter and displays the array.
A method which takes one integer array parameter and displays every element of the array at an even index.
A method which takes one integer array parameter and displays every odd element.
A method which takes one integer array parameter and prints the array in reverse order. You may not use a string to store the reverse, you can only print the array.
A method which takes one integer array parameter and prints only the first, middle, and last elements of the array. NOTE: An array with an even number of elements will have two middle elements, and an array with an odd number of elements will have only one middle element.
Write a main method which demonstrates the above methods. Ask the user for the size of the initial array.
Sample:
Solution
ArrayNumbersTest.java
import java.util.Random;
import java.util.Scanner;
public class ArrayNumbersTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print(\"Enter the number of elements: \");
int n = scan.nextInt();
int a[] = readArray(n);
displayArray(a);
evenIndexArrayDisplay(a);
oddElementArrayDisplay(a);
reverseArray(a);
firstMiddleLastElements(a);
}
public static int[] readArray(int n){
Random r = new Random();
int a[] = new int[n];
for(int i=0; i<n; i++){
a[i] = r.nextInt(20)+1;
}
return a;
}
public static void displayArray(int a[]){
System.out.print(\"Array: \");
for(int i=0; i<a.length; i++){
System.out.print(a[i]+\" \");
}
System.out.println();
}
public static void evenIndexArrayDisplay(int a[]){
System.out.print(\"Even Indexes: \");
for(int i=0; i<a.length; i++){
if(i % 2 == 0)
System.out.print(a[i]+\" \");
}
System.out.println();
}
public static void oddElementArrayDisplay(int a[]){
System.out.print(\"Odd Elements:: \");
for(int i=0; i<a.length; i++){
if(a[i] % 2 != 0)
System.out.print(a[i]+\" \");
}
System.out.println();
}
public static void reverseArray(int a[]){
System.out.print(\"Reverse: \");
for(int i=a.length-1; i>=0; i--){
System.out.print(a[i]+\" \");
}
System.out.println();
}
public static void firstMiddleLastElements(int a[]){
System.out.print(\"First, Middle, Last: \");
System.out.print(a[0]+\" \");
if(a.length % 2 == 0){
System.out.print(a[a.length/2]+\" \");
System.out.print(a[(a.length-1)/2]+\" \");
}
else{
System.out.print(a[a.length/2]+\" \");
}
System.out.print(a[a.length-1]+\" \");
}
}
Output:
Enter the number of elements: 10
Array: 11 17 6 5 1 9 2 10 12 2
Even Indexes: 11 6 1 2 12
Odd Elements:: 11 17 5 1 9
Reverse: 2 12 10 2 9 1 5 6 17 11
First, Middle, Last: 11 9 1 2

