Java程式問題

請問要如何使用do-while迴圈修改下面的程式碼使輸入的字串能夠限制在5個字元?還有如使每個字元之間能夠空一個字元?

package test10;

import java.util.*;

public class T10 {

public static void main(String args[]){

Scanner sc=new Scanner(System.in);

do{

System.out.println("請輸入字串:");

String str = sc.nextLine();

}while();

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

System.out.print("輸出:"str.charAt(i-1));

}

}

}

程式執行完大概是像這樣

請輸入字串:12345

輸出:5 4 3 2 1

1 個解答

評分
  • John
    Lv 7
    7 年前
    最佳解答

    import java.util.*;

    public class T10 {

    public static void main(String[] args) {

    final int MAX_CHAR = 5;

    char[] chars = read("請輸入字串: ", MAX_CHAR);

    print("輸出: ", chars);

    System.exit(0);

    }

    private static void print(String message, char[] value) {

    System.out.print(message);

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

    System.out.printf("%s ", value[i]);

    }

    System.out.println();

    }

    /*

    * It should use for-loop, instead of do-while-loop; if array size is defined.

    */

    private static char[] read(String message, int max) {

    System.out.print(message);

    Scanner keyboard = new Scanner(System.in);

    String input = keyboard.nextLine();

    char[] chars = new char[max];

    int idx = 0;

    do {

    try {

    chars[idx] = input.charAt(idx);

    } catch (Exception ignore) {

    chars[idx] = '?';

    } finally {

    idx++;

    }

    } while (idx < max);

    return chars;

    }

    }

還有問題?馬上發問,尋求解答。