1

I have to build a program Vocabulary with ArrayList. The words are added in this ArrayList. Then I have to check whether the word inputted:

  1. has more than two
  2. is only one word
  3. does not contain certain characters.

At the end I have to check words in list with the three first characters of the string inputted and return the words found. Here is my code:

import java.util.ArrayList;
import java.util.Scanner;

public class Vocabulary {

    public static void main(String[] args) {
        ArrayList<String> vocabularyList=new ArrayList<String>();

        vocabularyList.add("vocabulary");
        vocabularyList.add("article");
        vocabularyList.add("java");
        vocabularyList.add("program");
        vocabularyList.add("calendar");
        vocabularyList.add("clock");
        vocabularyList.add("book");
        vocabularyList.add("bookshop");
        vocabularyList.add("word");
        vocabularyList.add("wordpress");

        Scanner input=new Scanner(System.in);

        System.out.println("Enter the word: ");
        String wordInputed=input.nextLine();

        input.close();
    }

    private static boolean isValidInput(String wordInputed){
        boolean result=true;

        if (wordInputed.trim().length()<2){
                System.out.println("Please enter a full word");
                result=false;
            }
            else if(wordInputed.trim().indexOf(" ")>-1){
                System.out.println("Please enter only one word");
                result=false;
            } 
            else if(wordInputed.trim().toLowerCase().contains("%") || wordInputed.trim().toLowerCase().contains("@") || wordInputed.trim().toLowerCase().contains("&")  ){
                System.out.println("Please enter an word that doesnt contains character: %, & and @");
                result=false;
            }
        return result;
    } 

} 
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
ani
  • 13
  • 4
  • 2
    Are you getting an error? What's the question? โ€“ Austin Oct 29 '15 at 21:50
  • Just a note, using wordInputed.trim().toLowerCase().contains() is unnecessary in the context of your final else if statement. For future reference: It isn't causing any problems, but eliminating unneeded portions of code greatly increases readability. โ€“ CodeLover Oct 29 '15 at 21:58
  • thanks for the opinion :) what would u suggests me to use? in fact, i have changed the code only for the post(the characters were "รง" and two other, similar to "c"), that's why i have turned the string in lowercase, i expected spaces with trim,etc... โ€“ ani Oct 29 '15 at 22:11

1 Answers1

0

If I understood your question correctly, you're looking for something like this:

if (isValidInput(input)) {
    String first3 = input.substring(0, 3);
    for (String word : vocabularyList) {
        if (word.startsWith(first3)) {
            System.out.println(word);
        }
    }
}
janos
  • 120,954
  • 29
  • 226
  • 236