首页 > 解决方案 > 我在学习 ArrayList 时被困在这一点上

问题描述

我正在学习 Java 中的 ArrayList。我正在制作一个猜词的程序。我从教程中复制并粘贴了一些代码。但我不知道如何使用它们。程序编译成功。但没有任何输出。这是代码

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class App {
    public static void main(String[] args) throws Exception {
//  Below 4 lines are mine. Trying to call methods.
        String[] ospd = { "hi,bye" };
        mustHaveAt('h', 0, loadWords(6, ospd));
        mustNotHave('h', loadWords(6, ospd));
    }

    public static List<String> loadWords(int len, String[] ospd) {
        List<String> words = new ArrayList<String>(1000);
        for (String word : ospd) {
            if (word.length() == len) {
                words.add(word);
            }
        }
        return words;
    }

    public static void mustHaveAt(char ch, int position, List<String> aList) {
        for (int i = aList.size() - 1; i >= 0; i--) {
            String word = aList.get(i);
            if (position >= word.length() || word.charAt(position) != ch) {
                aList.remove(i);
            }
           if (position < word.length() && word.charAt(position) == ch) {
        System.out.println("Word " + word + " has character " + ch + " at position " + position);
           }
        }
    }

    public static void mustNotHave(char ch, List<String> aList) {
        Iterator<String> itr = aList.iterator();
        while (itr.hasNext()) {
            String word = itr.next();
            if (word.indexOf(ch) >= 0) {
                itr.remove();
            }
        }
    }
}

标签: javaarraylist

解决方案


如果您想检查方法是否成功(猜测单词),请自己添加输出。

你可以这样做:

public static void mustHaveAt(char ch, int position, List<String> aList) {
    for (int i = aList.size() - 1; i >= 0; i--) {
        String word = aList.get(i);
        if (position >= word.length() || word.charAt(position) != ch) {
            aList.remove(i);
        }
        if (position < word.length() && word.charAt(position) == ch) {
            System.out.println("Word " + word + " has character " + ch + "at position " + position)
        }
    }
}

如果在单词的所需位置出现带有所需字母的单词,此代码将为您提供输出


推荐阅读