import java.io.*;
import java.lang.*;
import java.util.*;
public class CountWords_Spaces {
public static void main(String[] args) throws IOException {
String str = "Hello World";
int i = 0, w = 0, s = 0, l, j = 0;
l = str.length();
for (i = 0; i < l; i++) {
if (str.charAt(i) != ' ' && str.charAt(i) != '\t') {
w++;
while (str.charAt(i) != ' ' && str.charAt(i) != '\t') {
i++;
}
}
s++;
}
s--;
System.out.println(str.charAt(1));
System.out.println("No of Words: " + w);
System.out.println("No of Spaces: " + s);
}
}
每次增加i
时,您都必须测试未通过输入str
的长度。更改
while (str.charAt(i) != ' ' && str.charAt(i) != '\t') {
包括对i < l
之类的测试
while (i < l && str.charAt(i) != ' ' && str.charAt(i) != '\t') {
有了这一改变,我得到了
e
No of Words: 3
No of Spaces: 2