为什么我得到java.lang.StringIndexOutOfBoundsException? [英] Why am I getting java.lang.StringIndexOutOfBoundsException?
问题描述
我想编写一个程序,逐步打印单词,直到出现完整的句子。例如:我需要写(输入)和输出:
我
我需要
我需要
我需要写。
这是我的代码:
public static void main(String [] args){
String sentence =我需要写。;
int len = sentence.length();
int numSpace = 0;
System.out.println(句子);
System.out.println(len);
for(int k = 0; k< len; k ++){
if(sentence.charAt(k)!='\ t')
continue;
numSpace ++;
}
System.out.println(找到+ numSpace +\t in string。);
int n = 1;
for(int m = 1; m< = 3; m ++){
n = sentence.indexOf('\t',n-1);
System.out.println(ligne+ m + sentence.substring(0,n));
}
}
这就是我得到的:
我需要写。
在字符串中找到0。
线程main中的异常java.lang.StringIndexOutOfBoundsException:
字符串索引超出范围:-1 at
java.lang.String.substring(String .java:1937)at
split1.Split1.main(Split1.java:36)Java结果:1构建成功
(总时间:0秒)
我不明白为什么numSpace不计算空格的出现次数,也不知道为什么我没有得到正确的输出(即使我将numSpace替换为3)。
这看起来像是家庭作业,所以我的答案是一个提示。 / p>
提示:读取 String.indexOf
支付注意当找不到字符串/字符时返回的值所说的内容。
(事实上 - 即使这不是正式的家庭作业,你显然是一个Java初学者。初学者需要了解 javadocs 是第一个在使用时看的地方一种不熟悉的方法。)
I want to write a program that prints words incrementally until a complete sentence appears. For example : I need to write (input), and output:
I
I need
I need to
I need to write.
Here is my code:
public static void main(String[] args) {
String sentence = "I need to write.";
int len = sentence.length();
int numSpace=0;
System.out.println(sentence);
System.out.println(len);
for(int k=0; k<len; k++){
if(sentence.charAt(k)!='\t')
continue;
numSpace++;
}
System.out.println("Found "+numSpace +"\t in the string.");
int n=1;
for (int m = 1; m <=3; m++) {
n=sentence.indexOf('\t',n-1);
System.out.println("ligne"+m+sentence.substring(0, n));
}
}
and this is what I get:
I need to write.
16
Found 0 in the string.
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -1 at
java.lang.String.substring(String.java:1937) at
split1.Split1.main(Split1.java:36) Java Result: 1 BUILD SUCCESSFUL
(total time: 0 seconds)
I don't understand why numSpace doesn't count the occurrences of spaces, nor why I don't get the correct output (even if I replace numSpace by 3 for example).
This looks like homework, so my answer is a hint.
Hint: read the javadoc for String.indexOf
paying attention to what it says about the value returned when the string / character is not found.
(In fact - even if this is not formal homework, you are clearly a Java beginner. And beginners need to learn that the javadocs are the first place to look when using an unfamiliar method.)
这篇关于为什么我得到java.lang.StringIndexOutOfBoundsException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!