私は値を入力するようにユーザーに求めているメソッドを実装しました。上記の値が範囲外であるか、正しい値のタイプでない場合は、エラーメッセージが表示され、再度確認する必要があります。スキャナを使用して正しい入力値を取得する
public static Integer getValue (Integer minValue, Integer maxValue) {
Scanner input;
input = new Scanner (System.in);
Integer value;
value = null;
while (true) {
try {
value = input.nextInt();
input.nextLine();
if ((value >= minValue) && (value <= maxValue)) {
break;
} else {
// Shows message that says value is not in range.
continue;
}
} catch (InputMismatchException IME) {
// Shows message that says value is not an integer.
input.next();
continue;
}
}
input.close();
return(value);
}
コードは、望ましくない値が与えられたときに正しく識別できます。この問題は、値が実際に正しい場合に発生し、次にハングアップしてデバッガにかかります。
これは、実行の例です:
Select the type of furniture:
1. - Dresser.
2. - Shelf.
3. - Rectangular table.
4. - Round table.
You chose: abc // Asks again because the value entered is not int.
a b c
adsf
5 // Asks again because the value entered is not in range.
1 // Here it is when the compiler takes me to the debugger.
は、ここで私はこの時点過去の実行を強制した場合、何が起こるかです。それは私の下のメニューを示し、それは完全に別の値をユーザーに尋ねた後クラッシュ:
Select the type of wood.
1. - Mahogamy.
2. - Cherry-tree.
3. - Walnut.
4. - Pine tree.
5. - Oak tree.
You chose: Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
これは、それがメインから呼ばれています方法です:
furnitureMenu();
indexTree = getValue(minIndexFurniture, maxIndexFurniture);
woodMenu();
indexWood = getValue(minIndexWood, maxIndexWood);
それは私がこのメソッドは仕事を得ることが重要です上記のように、私はメニューから選択するだけでなく、寸法などの家具の仕様を取得するために、何度かユーザーからの入力を必要とするためです。
すべてのご協力をいただきありがとうございます。前もって感謝します。
私のコンピュータでこの機能を実行しても問題はありませんでした。 –
@FallaCoulibalyあなたはあなたのメインの中でそれをもう一度呼び出すことができますか、それが私のためにしたようにハングアップまたはクラッシュするかどうかを確認できますか? – ShadowGeist
私はこのようなメインからそれを呼び出しました。Integer indexTree = getValue(0、4); –