猿问

如何检查 String[] 是否包含我的元素?

我被要求编写一个代码,将元素添加到具有一些条件的数组中。我搜索了整个 StackOverflow 以了解如何在数组中查找元素,但都给了我错误,所以我猜我的代码有问题,我不知道是什么。任何帮助表示赞赏。


public class WordList

{

    String [] words;

    int count = 0;

    int max = 2;


    WordList()

    {

        words = new String[max];

        this.words = words;

        this.count = count;

    }


    public static void main (String[] args)

    {

        WordList w1 = new WordList();

        System.out.println(w1.addWord("Dog"));

        System.out.println(w1.addWord("Cat"));

        System.out.println(w1.addWord("Fish"));

    }


    public int addWord(String newWord)

    {


        for(int i = 0; i < words.length; i++)

        {

            if(words.contains(newWord) == false && words.length < max)

            {

                words[i] = newWord;

            }

            else if(words.contains(newWord) == false && words.length == max)

            {

                max *= 2;

                words[i] = newWord;

            }




            count = i + 1;

        }

        return count;

    }


森栏
浏览 260回答 3
3回答

江户川乱折腾

我认为您可以使用Set而不是数组。public class WordList {&nbsp; &nbsp; private final Set<String> words = new HashSet<>();&nbsp; &nbsp; public int addWord(String word) {&nbsp; &nbsp; &nbsp; &nbsp; if (word != null)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; words.add(word);&nbsp; &nbsp; &nbsp; &nbsp; return words.size();&nbsp; &nbsp; }&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; WordList w1 = new WordList();&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(w1.addWord("Dog"));&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(w1.addWord("Cat"));&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(w1.addWord("Fish"));&nbsp; &nbsp; }}

繁星淼淼

我认为这就是你想要做的。常规数组没有indexOforcontains方法,所以你需要使用Arrays(确保你也导入它)public int addWord(String newWord){&nbsp; List <String> myList = Arrays.asList(words);&nbsp; &nbsp; for(int i = 0; i < words.length; i++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if(myList.indexOf(newWord) == -1 && words.length < max)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; words[i] = newWord;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else if(myList.indexOf(newWord) == -1 && words.length == max)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; max *= 2;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; words[i] = newWord;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; count = i + 1;&nbsp; &nbsp; }&nbsp; &nbsp; return count;}

MMTTMM

无论如何,您都需要编写自己的方法来找到它。它不受内存限制 - 您可以将数组转换为 List 并使用 .contains() 方法。Arrays.asList(words).contains(newWord);否则,您可以使用流来查找元素。Arrays.stream(words).anyMatch(newWord::equals);
随时随地看视频慕课网APP

相关分类

Java
我要回答