【问题标题】:Finding multiple set of given words in a paragraph array在段落数组中查找多组给定单词
【发布时间】: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 &lt;=10 ; j++) { 更改为for(int j = 0 ;j &lt;divie.length ; j++) {
  • @Typhon 非常感谢你:D

标签: java arrays search find


【解决方案1】:

这是一个工作代码,将其与您的代码进行比较并找出问题:

public static void main(String[] args)


{
     String paragraph[] = {"Hello my name is","Jack the reaper", "what up"};
     String toBeSearched;
     String curSearch;
     boolean intIndex = false ;
    
     
     System.out.printf("enter string:");
     Scanner myScanner = new Scanner(System.in);
     toBeSearched = myScanner.nextLine();
    
 String[] divide = toBeSearched.split(" ");
 

 for(int i = 0; i < divide.length ; i ++) {
     String word = divide[i];
     for(int y = 0; y < paragraph.length ; y++) {
         if(paragraph[y].contains(word)) {
             System.out.println(word+ "found at line: "+ y);
         }
     }
     
 }

}

【讨论】:

  • 非常感谢!!
猜你喜欢
  • 1970-01-01
  • 2020-08-18
  • 2013-12-19
  • 2021-06-13
  • 1970-01-01
  • 2021-12-14
  • 2019-07-31
  • 2012-07-07
  • 1970-01-01
相关资源
最近更新 更多