数组重复元素

发布于 2024-12-02 20:34:01 字数 436 浏览 3 评论 0原文

我试图要求用户输入元素,但如果用户输入重复的元素,我的方法应该返回 false。到目前为止,这就是我所拥有的...提前谢谢您!

public boolean setGuess(int index, int value) // required by instructor
{ 
    int [] guesses = new int[countVal]; //countVal is array length
    for (int i = 0; i < guesses.length; i++)
        for (int j = 0; j < i; j++)
        {
            if (guesses[i] == guesses[j])
                return false;
        }
    return true;
}

I am trying to ask a user to input elements, but if the user inputs a repeated element my method should return false. So far this is what I have... Thank you in advance!

public boolean setGuess(int index, int value) // required by instructor
{ 
    int [] guesses = new int[countVal]; //countVal is array length
    for (int i = 0; i < guesses.length; i++)
        for (int j = 0; j < i; j++)
        {
            if (guesses[i] == guesses[j])
                return false;
        }
    return true;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

难如初 2024-12-09 20:34:01
boolean hasRepeatedElement = new HashSet(Arrays.asList(arr)).size() == arr.length;
boolean hasRepeatedElement = new HashSet(Arrays.asList(arr)).size() == arr.length;
丢了幸福的猪 2024-12-09 20:34:01

尽管您没有提出真正的问题,但很明显您会遇到麻烦,因为您分配了一个整数数组,但从未用任何东西填充它们。然后你开始寻找重复项。

如果您的问题是“这对我不起作用”,那么这是一个值得一看的地方。

另一个是您有一个名为 setGuess 的方法,它听起来根本不像一个应该查找重复项的方法。事实上,它被称为 setGuess 并且是“讲师要求的”,这意味着这项作业比您的问题中包含的内容要多得多。

考虑扩大问题,然后我可以撤回这个答案,这个答案对于评论来说太长了......

Although you did not ask a real question, it is fairly obvious you are going to get into trouble because you allocated an array of integers but never filled them with anything. Then you starting looking for duplicates.

If your question was "this doesn't work for me" then this is one place to look.

Another is that you have a method called setGuess which does not at all sound like a method that should look for duplicates. The fact that it is called setGuess and is "required by instructor" means there is much more to this assignment than you have in your question.

Consider expanding the question, then I can withdraw this answer, which was too long for a comment....

等你爱我 2024-12-09 20:34:01

更多内容在同一问题中
1. 可以使用 countVal 代替 guesses.length
2. “int index, int value”参数有什么用,你没有在方法中使用。
3. 声明 guesses[] 将在所有索引处只有 0,因此 "guesses [i] ==guesses[j]" 没有任何意义。

尝试回答以上所有要点,将帮助您更好地编码。

More over in the same Question
1. in place of guesses.length u can use countVal.
2. Whats the use of "int index, int value" parameters, you are not using in the method.
3. declaring guesses[] will will have only 0 at all the indexes, so "guesses [i] == guesses[j]" has no meaning.

Try to answer all the above points, will help you code better.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文