そこで、Javaの標準パッケージを使用して、入力整数を読み取る効率的な方法を探していました...たとえば、クラス「Scanner」に出くわしましたが、2つの主な問題が見つかりました。
- intを挿入しないと、実際には例外を解決できません。
- このクラスはトークンで機能しますが、私の目的は文字列を完全な長さでロードすることです。
これは私が実現したい実行の例です:
Integer: eight
Input error - Invalid value for an int.
Reinsert: 8 secondtoken
Input error - Invalid value for an int.
Reinsert: 8
8 + 7 = 15
そして、これは私が実装しようとした(間違った)コードです:
import java.util.Scanner;
import java.util.InputMismatchException;
class ReadInt{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
boolean check;
int i = 0;
System.out.print("Integer: ");
do{
check = true;
try{
i = in.nextInt();
} catch (InputMismatchException e){
System.err.println("Input error - Invalid value for an int.");
System.out.print("Reinsert: ");
check = false;
}
} while (!check);
System.out.print(i + " + 7 = " + (i+7));
}
}