【发布时间】:2021-06-12 22:19:09
【问题描述】:
我正在字符串数组中搜索单词,如果找到我想返回他们的行。 我试图将搜索到的输入划分为一个数组,然后在段落数组中逐行搜索它。这实际上不起作用。
public static void main(String[] args) {
String paragraph[] = new String[10];
String toBeSearched;
String curSearch;
boolean intIndex = false ;
paragraph[0] = "Hello my name is";
paragraph[1] = "Jack the reaper";
paragraph[2] = "what up";
System.out.printf("enter string:");
Scanner myScanner = new Scanner(System.in);
toBeSearched = myScanner.nextLine();
String[] divide = toBeSearched.split(" ");
for(int j = 0 ;j <=10 ; j++) {
curSearch = divide[j];
for (int k = 0; k <=paragraph[j].length() ; k++) {
intIndex = paragraph[j].contains(curSearch);
if(intIndex == true) {
System.out.printf("Found at line %d \n",j );
}
}
}
假设我一次最多可以搜索 10 个单词。
假设用户输入:“Hello name the up” 我想要答案:在第 1 行 在第 1 行 在第 2 行 在第 3 行
如果我在段落的第 2 或第 3 索引中询问一个单词,它不起作用我不明白为什么(没有收到错误消息)
【问题讨论】:
-
divide数组的大小是未知的,基本上每次用户输入一个句子都会改变。用`for(int j = 0 ;j Hello From Stackoverflow* 的大小是 divide 数组将为 3 并且与 for 循环的逻辑一起使用,您将尝试索引 divide的第 4..10 个元素> 它们不存在的数组,因为数组的大小是 3 而不是 10 。将
for(int j = 0 ;j <=10 ; j++) {更改为for(int j = 0 ;j <divie.length ; j++) { -
@Typhon 非常感谢你:D