Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

(Intro to Java help?) Write a static method named rotateRight that accepts an ar

ID: 3699324 • Letter: #

Question

(Intro to Java help?)

Write a static method named rotateRight that accepts an array of integers as a parameter and rotates the values in the array to the right (i.e., forward in position) by one. Each element moves right by one, except the last element, which moves to the front. For example, if a variable named list refers to an array containing the values {3, 8, 19, 7}, the call of rotateRight(list) should modify it to store {7, 3, 8, 19}. A subsequent call of rotateRight(list) would leave the array as follows: {19, 7, 3, 8}.

Test your code with the following class:

import java.util.*;

public class TestRotateRight {

    public static void main(String[] args) {

        int[] list = {3, 8, 19, 7};

        rotateRight(list);

        System.out.println(Arrays.toString(list));   // [7, 3, 8, 19]

        rotateRight(list);

        rotateRight(list);

        System.out.println(Arrays.toString(list));   // [8, 19, 7, 3]

        rotateRight(list);

        System.out.println(Arrays.toString(list));   // [3, 8, 19, 7]

        rotateRight(list);

        rotateRight(list);

        rotateRight(list);

        System.out.println(Arrays.toString(list));   // [8, 19, 7, 3]

        rotateRight(list);

        rotateRight(list);

        rotateRight(list);

        rotateRight(list);

        System.out.println(Arrays.toString(list)); // [8, 19, 7, 3]

    }

    // your code goes here

}

Explanation / Answer

import java.util.Arrays;

public class TestRotateRight {

   public static void main(String[] args) {

       int[] list = { 3, 8, 19, 7 };

       rotateRight(list);

       System.out.println(Arrays.toString(list)); // [7, 3, 8, 19]

       rotateRight(list);

       rotateRight(list);

       System.out.println(Arrays.toString(list)); // [8, 19, 7, 3]

       rotateRight(list);

       System.out.println(Arrays.toString(list)); // [3, 8, 19, 7]

       rotateRight(list);

       rotateRight(list);

       rotateRight(list);

       System.out.println(Arrays.toString(list)); // [8, 19, 7, 3]

       rotateRight(list);

       rotateRight(list);

       rotateRight(list);

       rotateRight(list);

       System.out.println(Arrays.toString(list)); // [8, 19, 7, 3]

   }

   private static void rotateRight(int[] list) {

       int arrLength = list.length;

       int lastElement = list[arrLength - 1];

       for (int i = arrLength - 1; i > 0; i--) {

           list[i] = list[i-1];

       }

       list[0] = lastElement;

   }

}