Note that there are some explanatory texts on larger screens.

plurals
  1. POshifting elements in an array to the right, returning second largest, removing elements (beginning java)
    text
    copied!<p>Write array methods that carry out the following tasks for an array of integers by completing the ArrayMethods class below:</p> <pre><code>public class ArrayMethods { private int[] values; public ArrayMethods(int[] initialValues) { values = initialValues; } public void shiftRight() {.......} public int returnSecondLargest {......} </code></pre> <ul> <li>Shift 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 9 16</li> <li>Return the second-largest element in the array</li> <li>Remove the middle element if the array length is odd, or the middle two elements if the length is even</li> </ul> <p>For the shifting method I have this:</p> <pre><code>public void shiftRight(){ for(int i=0; i&lt;=values.length-1; i++){ if(i&lt;values.length){ values[i]=values[i+1]; } else if(i==values.length+1){ values[i]=values[0]; } } </code></pre> <p>For the returning second largest method I have this:</p> <pre><code>public int returnSecondLargest(){ int temp; for (int i = 0; i &lt; values.length-1; i++) { if(values[i] &gt; values[i+1]){ temp = values[i]; values[i] =values[i + 1]; values[i+1] = temp; } } return values[values.length - 2]; } </code></pre> <p>And for the removing middle element method I have this:</p> <pre><code>public void removeMiddleElement(){ int count = 0; for(int i=0; i&lt;values.length; i++){ count++; if(count%2==0){ int middle1=count/2; int middle2=(count/2)+1; int[] copy = new int[values.length -1]; System.arraycopy(copy, 0, copy, 0, middle1); System.arraycopy(copy, middle1+1, copy, middle1, copy.length-middle1-1); System.arraycopy(copy, 0, copy, 0, middle2); System.arraycopy(copy, middle2+1, copy, middle2, copy.length-middle2-1); copy = values; } else if(count%2!=0){ int middle3=(int) ((count/2)+.5); int[] copy = new int[values.length -1]; System.arraycopy(copy, 0, copy, 0, middle3); System.arraycopy(copy, middle3+1, copy, middle3, copy.length-middle3-1); copy = values; } } } } </code></pre> <p>In each of my methods I've gotten 'out of bounds' errors or they've just appeared to do nothing and return the original array with no changes made. If you see any glaring errors or have any advice it would be much appreciated :) Thanks!</p> <p>edit: removeMiddleElement appears to do nothing, the other two methods give out of bounds errors at the line that says values[i+1]</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload