-4

私は次の問題を抱えています: ユーザーから文字列を読み込みたいのですが、これまでのところうまくいきますが、「リターン」を押すたびに常に次のエラーが発生します:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    at java.lang.String.charAt(String.java:658)
    at Shell.execute(Shell.java:20)
    at Shell.main(Shell.java:55)

これはコードになります:

private static void execute(BufferedReader stdin) throws IOException {
    boolean quit = false;
    Field test = new Field();
    while (!quit) {
        System.out.print("ch> ");
        String input = stdin.readLine();
        if (input == null) {
                break;
        }
        String[] tokens = input.trim().split("\\s+");
        tokens[0].toLowerCase();
        char tmp = tokens[0].charAt(0);
        switch (tmp) {
        case 'n':
                test.setPoints(null);
                break;
        case 'a':
                test.add(new Point(Integer.parseInt(tokens[1]), Integer
                        .parseInt(tokens[2])));
                break;
        case 'r':
                test.remove(new Point(Integer.parseInt(tokens[1]), Integer
                        .parseInt(tokens[2])));
                break;
        case 'p':
                System.out.println(test);
                break;
        case 'c':
                System.out.println(test.convexHull());
                break;
        case 'h':
                System.out.println("");
                break;
        case 'q':
                quit = true;
                break;
        default:
                break;
        }
    }
}

ご協力いただきありがとうございます。

4

5 に答える 5

2

0番目の要素にアクセスするときにインデックスの範囲外の例外が発生した場合、文字列はおそらく空です。これをチェックする必要があります。nullをチェックするだけでは不十分です。

ちなみに、このように書くと:

tokens[0].toLowerCase();

あなたのtokens[0]は変更されていないのではないかと思います。Javaの文字列は不変であるため、toLowerCaseは小文字のみを含む新しい文字列を返す必要があります。

于 2012-10-23T09:17:03.503 に答える
0

ユーザー入力が空の文字列であることは明らかです。分割する前に空文字列チェックを入れます。

if (input == null && input.isEmpty()) {
    break;
}
于 2012-10-23T09:22:59.537 に答える
0

tokens問題が発生していると思われるため、分割後に配列に文字列が入力されているかどうかを確認してください。

于 2012-10-23T09:19:13.823 に答える
0

リターンを押した場合、入力文字列は空です。コードを次のように変更して修正します。

while (!quit) {
     System.out.print("ch> ");
     String input = stdin.readLine();
     if (input == null && input.length()<1) { //changed line!
          break;
     }
      String[] tokens = input.trim().split("\\s+");
于 2012-10-23T09:20:27.633 に答える
0

ここに問題があります

String input = stdin.readLine();
        if (input == null) {
                break;
        }

ここで「return」を押しても null は返されず、if 条件が失敗します。

コードは以下の行で失敗します

tokens[0].toLowerCase();
于 2012-10-23T09:21:14.017 に答える