く保証の整数を介して入力スキャナー?
-
19-08-2019 - |
質問
プログラムを皆様にお伝えしたくて書き込みながらプレーする必要がありまをお願いユーザーのための整数と1-8.された複数の(クリーナー)を行いこなしていたので、私がこの:
int x = 0;
while (x < 1 || x > 8)
{
System.out.print("Please enter integer (1-8): ");
try
{
x = Integer.parseInt(inputScanner.next());
}
catch(NumberFormatException e)
{
x = 0;
}
}
場所 inputScanner
が読み取ってくれます。はあるのではないでしょうかよりよい。
解決
スキャナーは正規表現を実行しますか? <!> quot; ^ [1-8] $ <!> quot;と一致するかどうかを確認してください。最初に?
他のヒント
nextInt()を使用することは、単にnext()メソッドを使用することと比較してすでに改善されています。そしてその前に、hasNextInt()を使用して、この無意味な例外の束をすべて回避することができます。
次のような結果になります:
int x = 0;
do {
System.out.print("Please...");
if(scanner.hasNextInt()) x = scanner.nextInt();
else scanner.next();
} while (x < 1 || x > 8);
グラフィックインターフェイスの計算機を実行する必要がありました(整数のみで動作します)。問題は、 入力ではない場合、テストでは例外をスローできませんでした 整数。使用できませんでした
try { int x = Integer.parseInt(input)} catch (Exception e) {dosomethingelse}
通常、JavaプログラムはJTextFieldへの入力を文字列として扱うため これを使用しました:
if (input.matches("[1-9][0-9]*"){ // String.matches() returns boolean
goodforyou
} else {
dosomethingelse
}
// this checks if the input's (type String) character sequence matches
// the given parameter. The [1-9] means that the first char is a Digit
// between 1 and 9 (because the input should be an Integer can't be 0)
// the * after [0-9] means that after the first char there can be 0 - infinity
// characters between digits 0-9
これが役に立てば幸いです:)
Apache Commonsはあなたの友達です。 NumberUtils.toInt(String、int)
String input;
int number;
while (inputScanner.hasNextLine())
{
input = inputScanner.nextLine();
if (input.equals("quit")) { System.exit(0); }
else
{
//If you don't want to put your code in here, make an event handler
//that gets called from this spot with the input passed in
try
{
number = Integer.parseInt(input);
if ((number < 1) || (number > 8))
{ System.out.print("Please choose 1-8: "); }
else { /* Do stuff */ }
}
catch (NumberFormatException e) { number = 0; }
}
}
いつものようにプの文字列だっていることをご確認くださいユーザーに押された入力ボタンを押します。まだ利用 inputScanner.nextInt()
できるだ int
sラインでアップします。
サンプルコード:
int x;
Scanner in = new Scanner(System.in);
System.out.println("Enter integer value: ");
x = in.nextInt();
整数を格納するために配列を使用することもできます。
次のようなものを試すことができます:
Scanner cin = new Scanner(System.in);
int s = 0;
boolean v = false;
while(!v){
System.out.print("Input an integer >= 1: ");
try {
s = cin.nextInt();
if(s >= 1) v = true;
else System.out.println("Please input an integer value >= 1.");
}
catch(InputMismatchException e) {
System.out.println("Caught: InputMismatchException -- Please input an integer value >= 1. ");
cin.next();
}
}
所属していません StackOverflow