0

教科書で練習問題を作成して、整数 (負と正) を配列に追加しています。ユーザーが最後に到達する前に配列への数字の入力を終了できるようにしたい [50]。

これは私が思いついたものです:

ユーザーは、文字列に格納されている数値を入力します。keepLo​​oping が true で、index < 配列のサイズの場合。文字列をトークンごとに解析し、数値を int 配列に配置します。

これを行うにはもっと簡単な方法が必要であり、コードを機能させることができません。どんな助けも大歓迎です:

// Create Objects to use in program
    Scanner keyboard = new Scanner(System.in);
    int[] arrayOfNumbers = new int[50];


    // Prompt for input
    System.out.println("Enter upto 50 integers separated by a space.");
    System.out.println("Type x to signal no more integers to enter.");

    int index = 0;
    boolean keepLooping = true;

    while (index < arrayOfNumbers.length && keepLooping) {
        String numToAdd = keyboard.nextLine();

        if ( numToAdd.equals("x") || numToAdd.equals("X") ) {
            keepLooping = false;
        }

        if ( !numToAdd.equals("x") || !numToAdd.equals("X") ) {
            arrayOfNumbers[index] = Integer.parseInt(numToAdd); 
        }
    }

    // DEBUG, Print Array
    for (int k=0; k < arrayOfNumbers.length; k++) {
        System.out.println(arrayOfNumbers[k]);
    }
4

3 に答える 3

2

プログラムを段階的にデバッグした場合 (Eclipse でのステップ実行など)、の値が変化しないF6ことに気付くでしょう。index最も速い修正は次のとおりです。

while (index < arrayOfNumbers.length && keepLooping) {
    String numToAdd = keyboard.nextLine();

    if ( numToAdd.equals("x") || numToAdd.equals("X") ) {
        keepLooping = false;
    }

    if ( !numToAdd.equals("x") || !numToAdd.equals("X") ) {
        arrayOfNumbers[index] = Integer.parseInt(numToAdd); 
    }

    index++;
}


しかしもちろん、これは配列の塗りつぶしの問題だけを解決します。次に、残りの回答で完全にカバーされているプログラミングの懸念事項の優れた実践について説明します。

于 2013-09-03T01:10:54.770 に答える
0
int index = 0;
boolean keepLooping = true;

while (index < arrayOfNumbers.length && keepLooping) {
    String numToAdd = keyboard.nextLine();

    if (numToAdd.equalsIgnoreCase("x")) { // Use EqualsIgnoreCase to shorten it
        keepLooping = false;
    } else { // Use an else statement instead of evaluating the inverse
        arrayOfNumbers[index] = Integer.parseInt(numToAdd); 
    }
    index++; // Increment the index to avoid eternal loop and actually fill the array
}
于 2013-09-03T01:11:17.953 に答える