2

そこで、Javaの標準パッケージを使用して、入力整数を読み取る効率的な方法を探していました...たとえば、クラス「Scanner」に出くわしましたが、2つの主な問題が見つかりました。

  1. intを挿入しないと、実際には例外を解決できません。
  2. このクラスはトークンで機能しますが、私の目的は文字列を完全な長さでロードすることです。

これは私が実現したい実行の例です:

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));
    }
}
4

2 に答える 2

1

トークンで使用するには:

int i = Integer.parseInt(in.next());

次に、次のことができます。

int i;
while (true) {
    System.out.print("Enter a number: ");
    try {
        i = Integer.parseInt(in.next());
        break;
    } catch (NumberFormatException e) {
        System.out.println("Not a valid number");
    }
}
//do stuff with i

上記のコードはトークンで機能します。

于 2013-01-10T13:58:15.587 に答える
1

BufferedReaderを使用します。NumberFormatExceptionを確認してください。それ以外はあなたが持っているものと非常に似ています。そのようです ...

import java.io.*;

public class ReadInt{
    public static void main(String[] args) throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        boolean check;
        int i = 0;
        System.out.print("Integer: ");
        do{
            check = true;
            try{
                i = Integer.parseInt(in.readLine());
            } catch (NumberFormatException 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));
    }
}
于 2013-01-10T14:01:27.713 に答える