这是我目前所拥有的,但是当我运行它时,我收到了 Java 不匹配错误。 这是我的数组:
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: " );
}
最佳答案
你可以这样做:
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) );
}
我只是将你的:letters.length-1
修改为 letters.length-2
并打印了数组。
另一种更简单的方法是使用 System.arraycopy
,例如:
last = letters[letters.length-1];
System.arraycopy(letters, 0, letters, 1, letters.length-1 );
letters[0] = last;
要打印数组,您还可以使用:
System.out.print("{");
for (int i=0;i<letters.length-1;i++)
System.out.print("'"+letters[i]+",");
System.out.println("'"+letters[letters.length-1]+"'}");
关于java - 向右移动数组 - 作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13129043/