java.lang.stringind,为什么我得到java.lang.StringIndexOutOfBoundsException?

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

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.)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值