Java中,如果数组包含重复的值返回true [英] Java, Return true if array contains duplicate values

查看:158
本文介绍了Java中,如果数组包含重复的值返回true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一个方法(重复)如果给定的阵列名为x(用户在其他方法进入)返回true,包含重复的值。否则,将返回false。而不是检查整个阵列,它被初始化为100,它将检查只输入的值的量,这是与一个全局计数器保持的轨道:numElementsInX

I am trying to have a method (duplicates) return true if a given array called x (entered by user in another method), contains duplicate values. Otherwise it would return false. Rather then checking the entire array, which is initialized to 100, it will check only the amount of values entered, which is kept track of with a global counter: numElementsInX.

什么是实现这一目标的最佳方式?

What is the best way to accomplish this?

public static boolean duplicates (int [] x)

我提示,像这样的用户数据:

I am prompting for user data like so:

public static void readData (int [] x, int i){

    Scanner input = new Scanner(System.in);
    System.out.println("Please enter integers, enter -999 to stop");

    while (i <= 99) {
        int temp = input.nextInt();
            if(temp == -999){
                break;
            }
            else {
                x[i++]=temp;
            }

    // else

}//end while
        printArray(x,i);


}//end readData

public static void printArray(int [] x, int numElementsInX){

int n = numElementsInX;

for (int i = 0; i < n; i++){
    System.out.print(x[i] + " ");


}//end for
        System.out.println();
}//end printArray

我肯定有一个更好的方式来做到这一点,但是这是我怎么迄今已教。

I am sure there is a better way to do this, but this is how I have been taught so far.

推荐答案

下面是一个解决方案是:

Here is a solution that:


  • 编译并没有抛出执行。

  • 使用 numElementsInX 为你的要求。

  • 只要它找到一个重复的回报。

  • Compiles and executes without throwing.
  • Uses numElementsInX as you requested.
  • Returns as soon as it finds a duplicate.

此方法测试是否数组中的每个成员都有过的。如果是,该方法可以立即返回。如果还没有,则该部件被添加到之前看到的集

This approach tests whether each member of the array has been seen before. If it has, the method can return immediately. If it hasn't, then the member is added to the set seen before.

public static boolean duplicates (int [] x, int numElementsInX ) {
    Set<Integer> set = new HashSet<Integer>();
    for ( int i = 0; i < numElementsInX; ++i ) {
        if ( set.contains( x[i])) {
            return true;
        }
        else {
            set.add(x[i]);
        }
    }
    return false;
}

下面是含有上述code 一个示例程序。

Here's a sample program containing the above code.

这篇关于Java中,如果数组包含重复的值返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆