java問題String[] myString

1.使用者決定繼續或是結束功能

2.對一個String[] myString = {&ldquo;*&rdquo;,&rdquo;A&rdquo;,&rdquo;B&rdquo;,&rdquo;C&rdquo;,&rdquo;D&rdquo;} 的陣列可以讓使用者選擇rotate left 或是 rotate right

3.選好後請列印rotate後的結果

NOTE:

Rating
• 1 decade ago

請參考我的做法

import java.util.*;

public class Y6752 {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

String[] myString = {"*","A","B","C","D"};

String s = null;

while (true) {

System.out.println(Arrays.toString(myString));

System.out.print("Rotate (L)eft, (R)ight, or (E)xit?");

s = scan.next();

if (s.equalsIgnoreCase("L")) { // rotate left

rotateLeft(myString);

} else if (s.equalsIgnoreCase("R")) { // rotate right

rotateRight(myString);

} else if (s.equalsIgnoreCase("E")) { // Exit

System.exit(0);

}

}

}

public static void rotateLeft(String[] ary) {

String first = ary[0];

for (int i = 0; i < ary.length-1; i++) {

ary[i] = ary[i+1];

}

ary[ary.length-1] = first;

}

public static void rotateRight(String[] ary) {

String last = ary[ary.length-1];

for (int i = ary.length-1; i > 0; i--) {

ary[i] = ary[i-1];

}

ary[0] = last;

}

}