在数组中打印不同的整数 [英] Printing distinct integers in an array

查看:96
本文介绍了在数组中打印不同的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个打印出数组中不同数字的小程序。例如,如果用户输入1,1,3,5,7,4,3,程序将仅打印出1,3,5,7,4。

I'm trying to write a small program that prints out distinct numbers in an array. For example if a user enters 1,1,3,5,7,4,3 the program will only print out 1,3,5,7,4.

我收到一个错误,如果行中的$ code> checkDuplicate 。

I'm getting an error on the else if line in the function checkDuplicate.

这是我的代码到目前为止:

Here's my code so far:

import javax.swing.JOptionPane;

public static void main(String[] args) {
    int[] array = new int[10];
    for (int i=0; i<array.length;i++) {
        array[i] = Integer.parseInt(JOptionPane.showInputDialog("Please enter"
                                  + "an integer:"));
    }
    checkDuplicate (array);
}

public static int checkDuplicate(int array []) {
    for (int i = 0; i < array.length; i++) {
        boolean found = false;
        for (int j = 0; j < i; j++)
            if (array[i] == array[j]) {
                found = true;
                break;
            }
        if (!found)
            System.out.println(array[i]);
    }
    return 1;
}
}


推荐答案

总而言之, else if 语句不正确,因为您不提供任何条件到if(如果你想要一个if,你需要写 if(condition)...

First of all, the "else if" statement is incorrect, since you don't provide any condition to the if (if you want an if, you need to write "if (condition) ...").

其次,你无法确定内部的 >循环,如果一个值应该被打印:你的代码的工作方式你为每个数组[j] 写数组[i] 不同于数组[i]!

Second, you cannot decide inside the inner loop, if a value should be printed: The way your code works you write a value array[i] for each value array[j] that is different from array[i]!

第三:内循环只需要从0到外部索引 i-1 :对于每个元素,只需要决定,如果它是第一次发生(即如果在任何之前的索引发生相同的值)。如果是,请打印出来,否则忽略它。

Third: the inner loop needs only to go from 0 to the outer index i-1: For each element, you need only to decide, if it is the first occurrence (i.e. if the same value occured at any previous index or not). If it is, print it out, if not, ignore it.

正确实现 CheckDuplicate()将是:

public static void checkDuplicate(int array []) {
  for (int i = 0; i < array.length; i++) {
    boolean found = false;
    for (int j = 0; j < i; j++)
      if (array[i] == array[j]) {
        found = true;
        break;
      }
    if (!found)
      System.out.println(array[i]);
  }
}

但当然,某种设置对于更大的数组将会更有效...

But of course, some kind of Set would be much more efficient for bigger arrays...

编辑:当然,由于 CheckDuplicate()不返回任何值,所以应该有返回类型 void (而不是 int )。我在上面的代码中纠正了这一点...

Of course, mmyers (see comments) is right by saying, that since CheckDuplicate() doesn't return any value, it should have return type void (instead of int). I corrected this in the above code...

这篇关于在数组中打印不同的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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