This is what I have so far, but when I run it, I get a Java mismatch error. This is my array:
char[] letters = {'A', 'B' , 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'};
/********************************************************************************
shiftRight() will move the contents of the array one slot to the right
********************************************************************************/
public static void shiftRight( char [] letters )
{
char last = letters[letters.length-1]; // save off first element
// shift right
for( int index =letters.length-1; index >= 0 ; index-- )
letters[index+1] = letters [index];
// wrap last element into first slot
letters[0] = last;
System.out.print("\nshifted Array: " );
}
You can do something like:
public static void shiftRight( char [] letters )
{
char last = letters[letters.length-1]; // save off first element
// shift right
for( int index =letters.length-2; index >= 0 ; index-- )
letters[index+1] = letters [index];
// wrap last element into first slot
letters[0] = last;
System.out.print("\nshifted Array: " + Arrays.toString(letters) );
}
I only modified your: letters.length-1
into letters.length-2
and printed the array.
Another, easier approach is to use, System.arraycopy
like:
last = letters[letters.length-1];
System.arraycopy(letters, 0, letters, 1, letters.length-1 );
letters[0] = last;
To print the array you can also use:
System.out.print("{");
for (int i=0;i<letters.length-1;i++)
System.out.print("'"+letters[i]+",");
System.out.println("'"+letters[letters.length-1]+"'}");
When letters[index+1]
is executed for the first time in the for-loop (when index = letters.length-1
), it's pointing to letters[letters.length]
which is not a valid index, since indexes go from 0
to length-1
.
Update your for-loop to start index
at letters.length-2
and also make sure your array.length>1
. That is to say:
if(letters.length > 1){ //make sure array has minimum two elements
// shift right
for( int index = letters.length-2; index >= 0 ; index-- ){
letters[index+1] = letters [index];
}
}
Also in the end, you may print the array as:
System.out.println("Shifted Array: " +letters);
EDIT: Sample working code.
If you make the array as Character
array e.g. below in your main
(this is required for assistance in printing ONLY)
Character[] letters = {'A', 'B' , 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'};
and then pass that to shiftRight
method with updated code as below:
public static void shiftRight( Character [] letters )
{
Character last = letters[letters.length-1];
if(letters.length >1){ //make sure array has minimum two elements
// shift right
for( int index =letters.length-2; index >= 0 ; index-- ){
letters[index+1] = letters [index];
}
}
letters[0] = last;
System.out.println(Arrays.toString(letters));
//^ prints: Shifted Array: [J, A, B, C, D, E, F, G, H, I]
}
You should be all set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With