StringIndexOutOfBoundsException字符串索引超出范围:0 [英] StringIndexOutOfBoundsException String index out of range: 0
问题描述
错误是与以下while循环,检查当前行
是否启动如果有一个非反斜杠字符,那么在while循环移动到下一行并再次检查时,使用空格或除'/'之外的任何字符。一旦while循环满足它的要求,并突破程序崩溃,我得到以下输出错误。
import java.rmi。命名;
import java.net.InetAddress;
i
import java.lang.reflect。*;
i
错误:String索引超出范围:0
在java.lang.String.charAt(未知来源)
在ExtraCredit.main(ExtraCredit.java:22)< /代码>< /预>
这里是有问题的代码示例
的System.out.println(线);
char x = line.charAt(0);
while((line.charAt(0)!='/')&&(Character.isWhitespace(x)== false))
{
line = inputFile.nextLine );
x = line.charAt(0);
System.out.println(line);
System.out.println(x);
}
感谢任何帮助。
当 line
为空(例如)。那么它在索引0中没有一个字符,因此你的错误。
要修复,您可以在使用 charAt 之前检查
行的长度
code>:
System.out.println(line);
char x;
if(line.length()< 1){
System.out.println(next line is empty);
} else {
x = line.charAt(0);
while((line.charAt(0)!='/')&&(Character.isWhitespace(x)== false))
{
line = inputFile.nextLine();
if(line.length()< 1){
System.out.println(next line is empty);
break;
}
x = line.charAt(0);
System.out.println(line);
System.out.println(x);
}
}
I am writing a program that opens a text file and checks for comments. It then parses through the comments to check for certain words.
The error im having is with the following while loop that checks to see if the current line starts with white space or any character other than '/' if there is a non backslash character there than the while loop moves on to the next line and checks again. Once the while loop meets its requirements and breaks out the program crashes and i get the following output error.
import java.rmi.Naming;
import java.net.InetAddress;
i
import java.lang.reflect.*;
i
ERROR: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at ExtraCredit.main(ExtraCredit.java:22)</code></pre>
here is the problematic code sample
System.out.println(line);
char x = line.charAt(0);
while((line.charAt(0)!='/')&&(Character.isWhitespace(x)==false))
{
line = inputFile.nextLine();
x = line.charAt(0);
System.out.println(line);
System.out.println(x);
}
thanks for any help. Im sure its a simple error but im just not seeing it.
The problem occurs when line
is empty (e.g. ""
). Then it doesn't have a character at index 0, hence your error.
To fix, you can check the length of line
before you use charAt
:
System.out.println(line);
char x;
if (line.length() < 1) {
System.out.println("next line is empty");
} else {
x = line.charAt(0);
while((line.charAt(0)!='/')&&(Character.isWhitespace(x)==false))
{
line = inputFile.nextLine();
if (line.length() < 1) {
System.out.println("next line is empty");
break;
}
x = line.charAt(0);
System.out.println(line);
System.out.println(x);
}
}
这篇关于StringIndexOutOfBoundsException字符串索引超出范围:0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!