【问题标题】:Java vocabulary program with arraylist带有arraylist的Java词汇程序
【发布时间】:2015-10-29 21:46:05
【问题描述】:

我必须用ArrayList 构建一个程序词汇表。在这个ArrayList 中添加了单词。然后我要检查是否输入了单词:

  1. 有两个以上
  2. 只有一个字
  3. 不包含某些字符。

最后,我必须使用输入的字符串的前三个字符检查列表中的单词并返回找到的单词。这是我的代码:

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

} 

【问题讨论】:

  • 您遇到错误了吗?有什么问题?
  • 请注意,在最后的 else if 语句中使用 wordInputed.trim().toLowerCase().contains() 是不必要的。供将来参考:它不会引起任何问题,但消除不需要的代码部分会大大提高可读性。
  • 感谢您的意见 :) 您建议我使用什么?事实上,我只更改了帖子的代码(字符是“ç”和另外两个,类似于“c”),这就是为什么我将字符串转为小写,我希望空格带有修剪等...

标签: java arraylist vocabulary


【解决方案1】:

如果我正确理解了您的问题,那么您正在寻找这样的东西:

if (isValidInput(input)) {
    String first3 = input.substring(0, 3);
    for (String word : vocabularyList) {
        if (word.startsWith(first3)) {
            System.out.println(word);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    • 1970-01-01
    • 2017-12-04
    相关资源
    最近更新 更多