Home > Mobile >  How do I find a word in an array and output it. In java
How do I find a word in an array and output it. In java

Time:03-15

Write a program that reads an integer, a list of words, and a character. The integer signifies how many words are in the list. The output of the program is every word in the list that contains the character at least once. For coding simplicity, follow each output word by a comma, even the last one. Add a newline to the end of the last output. Assume at least one word in the list will contain the given character. Assume that the list of words will always contain fewer than 20 words.

Ex: If the input is:

4 hello zoo sleep drizzle z

then the output is:

zoo,drizzle,

      String[] words = new String[20];
      String list = "";
      
      list = scan.next();
      
      for(int i = 0; i < list; i  )
      {
         words[i] = scan.next();
      }
      
      int searchChar = scnr.next().charAt(0);
      for (int i = 0; i < word[i]; i  )
      {
         if (words.indexOf(searchChar))
         {
            System.out.println(word[i]);
         }
         else
         {
            return -1;
   }
}
}
}

I am not receiving the correct output, there are a couple of errors in my code. Can someone guide me on what my errors are? Thank you.

CodePudding user response:

Your for loops aren't well constructed.

Instead of:

for(int i = 0; i < word[i]; i  )

Do:

for(int i = 0; i < word.length; i  )

Or if the size of the array (20) is a constant, you can use also that

In the case of the 1º loop is the same. What type is the list variable? If it's a string you should call the length method. If it is a collection, the size method

CodePudding user response:

You can simply use String.constains(CharSequence). You should use nextInt() for integer instead of String. Here is example:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String[] words = new String[20];
        int n;

        n = scan.nextInt();

        for (int i = 0; i < n; i  ) {
            words[i] = scan.next();
        }
        char searchChar = scan.next().charAt(0);
        CharSequence charSequence = new StringBuffer(1).append(searchChar);
        for (var i = 0; i < n; i  ) {
             if (words[i].contains(charSequence)) {
                 System.out.print(words[i]   ",");
             }
        }
        System.out.println();
    }
}

  • Related