-2

次の宿題の問題があります。

Q1. ネストされた for ループ ステートメントを使用して、任意の文字 (ユーザーからの入力) の空のボックスを描画します。ボックスの行数と列数は同じです (ユーザーからの入力、有効範囲: 5 から 21)。入力エラーのテスト (タイプを含む)

サンプル出力:

Do you want to start(Y/N): y
How many chars/last row? n
Not an integer! Try again! How many chars/last row? fgfgfg
Not an integer! Try again! How many chars/last row? 7.6
Not an integer! Try again! How many chars/last row? 34
ERROR! Valid range 5 - 21. How many chars/last row? 7
What character? k

Do you want to continue(Y/N): y

以下のコードを書きましたが、「n」または「N」を押しても終了しません。理由がわかりません。どうすればこれを修正できますか?

public static void main(String[] args) {
    Scanner input = new Scanner(System. in );
    char answer = 'n';
    int row = 0;
    char output = 'k';

    do {
        System.out.println("DO YOU WANT TO START Y OR N?");
        answer = input.next().charAt(0);
        System.out.println("enter the number of rows");

        while (!input.hasNextInt()) {
            System.out.println("Not an integer,try again ");
            input.next();
        }

        row = input.nextInt();


        while (row < 5 || row > 21) {
            System.out.println("ERROR! Valid range 5 - 21. How many chars/last row?");
            row = input.nextInt();
        }
        System.out.println("WHAT CHARACTER?");
        output = input.next().charAt(0);

        for (int i = 0; i < row; i++) { //nested for loop to create the box
            System.out.print(output);
        }
        System.out.println();

        for (int i = 0; i < row - 2; i++) {
            System.out.print(output);
            for (int j = 0; j < row - 2; j++) {
                System.out.print(" ");
            }
            System.out.print(output);
            System.out.println();
        }
        for (int i = 0; i < row; i++) {
            System.out.print(output);
        }
        System.out.println();
        System.out.println();
        System.out.println("DO YOU WANT TO CONTINUE ? Y OR N");
        answer = input.next().charAt(0);

    } while (answer == 'Y' || answer == 'y');

    input.close();
    System.out.println("game stop");
}
4

2 に答える 2

2

NafterDo you want to start(Y/N):とafter の条件を追加する必要がありますDo you want to continue(Y/N):

System.exit(0)プログラムを終了するために使用されます。

このコードを入れて

System.out.println("DO YOU WANT TO START Y OR N?");
    answer = input.next().charAt(0);
    if(answer == n || answer == N){
        System.exit(0);
    }

そして、これはDo you want to continue(Y/N):

System.out.println("DO YOU WANT TO CONTINUE ? Y OR N");
    answer = input.next().charAt(0);
    if(answer == n || answer == N){
        System.exit(0);
    }

編集

答えが の場合に 'Game Stop' を出力したい場合は、 beforeNを使用しますThread.sleep(timeInMilliseconds);System.exit(0)

if(answer == n || answer == N){
    Thread.sleep(5000); //This will make console wait for 5 seconds before exiting.
    System.out.println("Game Stop."); //game stop will be printed for 5 seconds
    System.exit(0);
}
于 2015-02-12T17:03:37.147 に答える