0

最終的に機能する例外をキャッチしようとしましたが、ループさせる方法を理解する必要があります。また、ループの外側にユーザ​​ー入力(int select)を取得するにはどうすればよいですか? 新しい関数を作成してみると、うまくいくかもしれません。

do {
    System.out.print("How many integers shall we compare? (Enter a positive integer): ");
    try {
        select = intFind.nextInt();
    } catch (InputMismatchException e) {
        // Display the following text in the event of an invalid input
        System.out.println("Invalid input!");
        intFind.nextLine();
    }
} while (select < 0);

それで

do
            {
                System.out.print("How many integers shall we compare? (Enter a positive integer): ");
                try {
                    b = Get();
                }
                catch (InputMismatchException e) {
                    // Display the following text in the event of an invalid input
                    System.out.println("Invalid input!");

                    intFind.nextLine();
                } copySel = b;  
            }while(select < 0);

static int Get()
    {
        Scanner intFind = new Scanner(System.in);
        int select;
        select = intFind.nextInt();
        return select;
    }
4

1 に答える 1

0

ループさせるにselectは、 が 0 未満の値に初期化されていることを確認してください。ただしselect < 2、少なくとも値と比較する方が理にかなっているからです。

のようなメソッドを作成します。

private int[] promptIntegers(int numberOfIntegers, Scanner sc) {
    int[] integers = new int[numberOfIntegers];
    //read ints
    //return the array
}

そしてそれを次のように呼び出します

select = intFind.nextInt();
int[] integers = promptIntegers(select, sc);
//do the comparison among the integers
于 2012-11-13T05:14:27.050 に答える