JAVA ONLY Write array methods that carry out the following tasks for an array of
ID: 3710199 • Letter: J
Question
JAVA ONLY
Write array methods that carry out the following tasks for an array of 10 integers. Start by using the random method to create 10 random integers between 1 and 100. Each of your methods (a-c below) will use this array. Each invocation of a method (a-c below) MUST use the original randomly created array. Use the main method to test all your other methods. Hint: You will be building 5 methods, including main, as part of your solution. Think through how arrays are passed to methods and decide how to retain original array. Build each method and test before going on to next method! Use import.java.util.Arrays
-Print array elements. Name this method printArray.
-Swap the first and last elements in the array. Name this method swapFirstLast.
-Replace all even elements with 0. Name this method replaceEven.
-Move all even elements to the front of array. Order of remaining elements not important. Name this method moveEven.
Explanation / Answer
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static int[] randomArray(){
int[] arr=new int[10];
Random rand = new Random();
for(int i=0;i<10;i++){
arr[i]=rand.nextInt(100);// use Random to generate random number between 0 to 100
}
return arr;
}
public static void printArray(int[] arr) {
for(int i=0;i<10;i++){
System.out.println(arr[i]);//print array element
}
}
public static void swapFirstLast(int[] arr){
int a=arr[0];//use temp variable to swap
arr[0]=arr[9];
arr[9]=a;
}
public static void replaceEven(int[] arr){
for(int i=0;i<10;i++){
if(i%2==0)
arr[i]=0;// change even elements to 0
}
}
public static void main (String[] args) throws java.lang.Exception
{
int[] arr=randomArray();
//any changes to array elements will be reflected in original array
printArray(arr);
swapFirstLast(arr);
replaceEven(arr);
printArray(arr);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.