我被困在这件事上找不到解决办法。在线程“java.lang.StringIndexOutOfBoundsException: String索引超出范围: 11”中获取异常错误。
有人能帮忙解决这个问题吗?我的代码:
public static void main(String[] args) {
try {
Scanner sc = new Scanner(new File("Testing.txt"));
int i = 0;
while(sc.hasNext()){
String line = sc.nextLine();
char needle = line.charAt(i);
while(i < line.length()){
if(Character.isUpperCase(needle)) {
while(needle != ' '){
System.out.print(needle);
i++;
needle = line.charAt(i);
}
System.out.println(needle);
}
else{
i++;
needle = line.charAt(i);
}
}
}
}
catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
}发布于 2017-03-13 08:01:09
根据我上面的注释,使用String split方法会更容易。当然,可以将input替换为文件中的文本,并使用expectedResult并测试输出是否等于,这完全是可选的。
public static void main(String[] args)
{
String input = "Kenny and I are eating in the Restaurant Yummy";
String expectedResult = "Kenny, I, Restaurant, Yummy";
String arr [] = input.split (" ");
StringBuilder out = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
if (Character.isUpperCase(arr[i].charAt(0))) {
out.append(arr[i]).append(", ");
}
}
if (out.length() > 1) {
out.setLength(out.length() -2);
}
System.out.println (out);
assert (expectedResult.equals(out.toString()));
} 输出
肯尼,我,餐厅,美味
发布于 2017-03-13 08:24:56
我的假设是你的错误会出现在这里;
i++;
needle = line.charAt(i);和
while(needle != ' '){
System.out.print(needle);
i++;
needle = line.charAt(i);
}因为您正在增加索引,而不检查索引是否存在。
发布于 2017-03-13 08:24:53
我不知道你想达到什么目的。但是从您的错误中,我可以说您正在尝试增加索引计数器,然后尝试访问您的字符串中的元素。
在while循环和else块中,有以下语句:
i++;
needle = line.charAt(i);将两者改为:
needle = line.charAt(i);
i++;您的代码将运行,没有上述异常。
更新
我做了上面提到的更改,并做了一些更改。
int i=0;的声明。对于文本文件中的多行,这是必需的。char needle = line.charAt(i);语句,因为您需要为每一行初始化指针。try (Scanner sc = new Scanner(new File("Testing.txt"))) {
while (sc.hasNext()) {
String line = sc.nextLine();
int i = 0;
while (i < line.length()) {
char needle = line.charAt(i);
if (Character.isUpperCase(needle)) {
while (needle != ' ' && i < line.length()) {
needle = line.charAt(i);
if(needle != ' '){
System.out.print(needle);
}
i++;
}
if(i < line.length()) {
System.out.print(", ");
}
} else {
needle = line.charAt(i);
i++;
}
}
System.out.println();
}
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}它输出以下输出:
Kenny, I, Restaurant, Yummy希望这能有所帮助!
https://stackoverflow.com/questions/42758795
复制相似问题