0

私はStringIndexOutOfBoundsException次のコードを取得しています。これがエラーです

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:694)
at Reflector.readConfig(Reflector.java:103)
at Reflector.run(Reflector.java:48)
at Reflector.main(Reflector.java:419)  

これがコードです

public int readConfig() {
    // validate the contents of the config file
    BufferedReader input=null;
    String name=null; 
    String value=null; 
    String inputLine=null;
    dest=new Hashtable();

    // open and read the config file
    try {
      input = new BufferedReader(new FileReader("reflector.conf"));
      inputLine=input.readLine();
    } catch (IOException e) {
      System.err.println("Error reading reflector.conf.");
      return(-1);
    }
    // loop until entire config file is read
    while (inputLine != null) {
      // skip comments:
      if (inputLine.charAt(0) != '#') {
        // extract a name/value pair, and branch
        // based on the name:
        StringTokenizer tokenizer = 
                            new StringTokenizer(inputLine,"="); 
        name = tokenizer.nextToken(); 
        value = tokenizer.nextToken(); 

        if (name == null) {
          System.out.println("no name"); 
          continue;
        } else if (name.equals(MODE)) {
          if (setMode(value) != 0) {
            System.err.println("Error setting mode to " + value);
            return(-1);
          } 

          }
        } else {
          System.err.println("Skipping invalid config file value: " 
                             + name);
        }
      }
      // read next line in the config file
      try {
        inputLine=input.readLine();
      } catch (IOException e) {
        System.err.println("Error reading reflector.conf.");
        return(-1);
      }
    }

    // close the config file
    try {
      input.close();
    } catch (IOException e) {
      System.err.println("Error closing reflector.conf.");
      return(-1);
    }

    // validate that the combined contents of the config file
    // make sense
    if (! isConfigValid()) {
      System.err.println("Configuration file is not complete.");
      return(-1);
    }
    return(0);
}
4

3 に答える 3

2

構成ファイルのどこかに空の行があるため、チェックif(inputLine.charAt(0) != '#')で例外がスローされます。readLine()は行末文字を読み取らないことに注意してください。

この問題を解決するには、空の行をスキップする明示的なチェックを追加します。最も簡単な修正は、次のようなことです。

if (!inputLine.isEmpty() && inputLine.charAt(0) != '#') {
于 2013-02-05T13:06:08.023 に答える
0

多分ここに:

inputLine.charAt(0)

最初の要素を参照し、文字列に少なくとも1つあるかどうかをチェックしません。この文字列が空でないかどうかを確認する必要があります。

于 2013-02-05T13:07:55.600 に答える
0

問題はここにあると思います:

if (inputLine.charAt(0) != '#') {

0インデックスの文字を比較しようとしていますが、変数inputLineに空の文字列が含まれている可能性があります""

したがって、この条件も確認する必要がありますinputLine.length() != 0

于 2013-02-05T13:08:51.667 に答える