promotion image of download ymail app
Promoted

java問題String[] myString

寫一支程式可以讓:

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

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

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

NOTE:

每一次rotate完畢請你更新原本myString陣列裡面位子的狀態。

每次只需要移動一格。

1 Answer

Rating
  • 1 decade ago
    Favorite Answer

    請參考我的做法

    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;

    }

    }

    • Commenter avatarLogin to reply the answers
Still have questions? Get your answers by asking now.