(Java)确定特定数字是否在ArrayList中出现两次

-3 java arraylist

问题是我需要某种方法来找出当要求输入特定数字时数组列表是否包含重复数字。

我得到的基本代码是:

public static boolean moreThanOnce(ArrayList<Integer> list, int number) {
    // write your code here
}

public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);

    ArrayList<Integer> list = new ArrayList<Integer>();

    list.add(3);
    list.add(2);
    list.add(7);
    list.add(2);

    System.out.println("Type a number: ");
    int number = Integer.parseInt(reader.nextLine());
    if (moreThanOnce(list, number)) {
        System.out.println(number + " appears more than once.");
    } else {
        System.out.println(number + " does not appear more than once.");
    }
}
Run Code Online (Sandbox Code Playgroud)

老实说,我需要帮助来决定要走的方向。由于如果对象出现两次或更多次,它需要工作,所以当它检测到出现特定数字时,我不能简单地翻转布尔值,因为如果该数字出现3次,它将失败。

我感谢有关如何进行的一些建议。

Dea*_*ool 5

您可以使用Collections.frequency(list, object)ArrayList中的出现对象计数

public static void main(String[] args) {
Scanner reader = new Scanner(System.in);

ArrayList<Integer> list = new ArrayList<Integer>();
   list.add(3);
   list.add(2);
   list.add(7);
   list.add(2);

 System.out.println("Type a number: ");
 int number = Integer.parseInt(reader.nextLine());
 if (Collections.frequency(list, number)>1 ) {
      System.out.println(number + " appears more than once.");
 } else {
  System.out.println(number + " does not appear more than once.");
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 我怀疑此练习的想法是使用库函数。 (3认同)
  • @VinceEmigh-在源代码中有很强的线索,OP提供了他正在进行某种“学习练习”的条件。另一个线索是他说:*“我得到的基本代码是:” *。另外,您说:*“我不相信SO是用于练习的。” *-我们知道...但是OP吗? (2认同)
  • @StephenC对不起,这是一个反问。我的观点是,这类问题很少能为网站带来价值。这个答案的唯一问题是,尽管这对其他人非常有用(因此赞成),但对OP的分配没有帮助。OP应当与他们的教授讨论的鼓励解决重复问题的答案,仅表明其他人可以发布和支持这样的内容。OleVV,尽管它可能适合家庭作业,但不适合重复,就像大多数与此类似的问题一样。 (2认同)
  • 对(非常)糟糕的问题的正确答案通常会引起反对意见(我赞成)。 (2认同)