In: Computer Science
Write array methods that carry out the following tasks for an array of integers by creating and completing the “ArrayMethods” class below. Add documentation comments for each method. Provide a test program called ‘Lab5_yourID.java” that test methods of ArrayMethods class. In your test program, use random class to generate array values.
public class ArrayMethods {
private int[ ] values; //declare instant variables
public ArrayMethods (int[ ] initialValues) {values = initialValues;} //constructor
public void shiftRight( ) { … }
public Boolean adjacentDuplicate( ) {…} }
Method shiftRight: that shifts all elements by one to the right and move the last element into the first position. For example, 1 4 9 16 25 would be transformed into 25 1 4 19 16.
Method adjacentDuplicate: returns true if the array has two adjacent duplicate elements.
Program Code Screenshot :
Sample Output
Program Code to Copy
import java.util.Arrays; class ArrayMethods { private int[] values; //declare instant variables public ArrayMethods(int[] initialValues) { values = initialValues; } public void shiftRight() { int t = values[values.length-1]; //Shift each element to right for(int i=values.length-1;i>=1;i--){ values[i] = values[i-1]; } //Shift last to first values[0] = t; } public Boolean adjacentDuplicate() { for(int i=1;i<values.length;i++){ //Check adjacent elements if(values[i]==values[i-1]){ return true; } } return false; } public String toString(){ return Arrays.toString(values); } } class Lab5_yourID { public static void main(String[] args) { ArrayMethods am = new ArrayMethods(new int[]{1,4,9,16,25}); System.out.println("Array is "+am); System.out.println("After shifting right"); am.shiftRight(); System.out.println(am); System.out.println("Adjacent duplicaets : "+am.adjacentDuplicate()); } }