简体   繁体   中英

Java vocabulary program with arraylist

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;
    } 

} 

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);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM