import java.io.*;
public class Search {
public static void main(String args[]) {
int first = 0, second =0, count = 0;
String text = "So that account you never had at a bank you never";
String s = "";
String subText = text;
System.out.println(text);
System.out.println("请输入单词");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
s = in.readLine();
} catch(IOException e){}
for(int i=1; i<=text.length();i+=second+1) {
second = subText.indexOf(" ");
String temp = subText.substring(first, second);
if(s.equalsIgnoreCase(temp)) count++;
subText = subText.substring(second+1);
}
if(count==0)
System.out.println("单词"+s+"没有出现");
else
System.out.println("单词"+s+"出现了"+count);
}
}
抛出StringIndexOutOfBoundsException
多多指点,小妹谢谢了
public class Search {
public static void main(String args[]) {
int first = 0, second =0, count = 0;
String text = "So that account you never had at a bank you never";
String s = "";
String subText = text;
System.out.println(text);
System.out.println("请输入单词");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
s = in.readLine();
} catch(IOException e){}
for(int i=1; i<=text.length();i+=second+1) {
second = subText.indexOf(" ");
String temp = subText.substring(first, second);
if(s.equalsIgnoreCase(temp)) count++;
subText = subText.substring(second+1);
}
if(count==0)
System.out.println("单词"+s+"没有出现");
else
System.out.println("单词"+s+"出现了"+count);
}
}
抛出StringIndexOutOfBoundsException
多多指点,小妹谢谢了
可以在前面加个判断,
if(second > 0){
String temp = subText.substring(first, second);
}
import java.io.*;
public class TestBuffer{
public static void main(String args[]) {
int count = 0;
String text = "So that account you never had at a bank you never";
String s = "";
System.out.println(text);
System.out.println("请输入单词");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
s = in.readLine();
} catch(IOException e){}
String[] textarr = text.split(" ");
for(int i=1; i <textarr.length;i++) {
String temp = textarr[i];
if(s.equalsIgnoreCase(temp)) count++;
}
if(count==0)
System.out.println("单词"+s+"没有出现");
else
System.out.println("单词"+s+"出现了"+count);
}
}