/ / Изключение в низа "main" java.lang.StringIndexOutOfBoundsException: Индекс на низове извън обхват - java, string, exception

Изключение в нишката "main" java.lang.StringIndexOutOfBoundsException: Струнен индекс извън обхвата - java, string, exception

Аз получавам 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);
}

Отговори:

2 за отговор № 1

Имате празен ред някъде в конфигурационния файл и следователно чека if(inputLine.charAt(0) != "#") хвърля изключението. Имайте предвид readLine() не чете символа за края на реда.

За да решите проблема, добавете явна проверка, за да пропуснете празни редове. Най-лесното решение е да направите нещо подобно:

if (!inputLine.isEmpty() && inputLine.charAt(0) != "#") {

0 за отговор № 2

Може би тук:

inputLine.charAt(0)

Вие препращате към първия елемент и не проверявайте какъв низ има поне един. Трябва да проверите преди този низ да не е празен.


0 за отговор № 3

Мисля, че проблемът е тук:

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

Опитвате се да сравните знака в 0 индекс, но променливата inputLine може да има празен низ "",

така че трябва да проверите това състояние inputLine.length() != 0