【问题标题】:How can I print the number of times a value appears in an array without the print statement repeating the same value?如何打印一个值在数组中出现的次数,而不需要打印语句重复相同的值?
【发布时间】:2021-09-07 17:34:09
【问题描述】:

我正在处理一项硬件分配,该分配要求编写一个名为 count 的方法,该方法确定目标值在数组中出现的次数。例如,如果您的数组是 [2, 3, 3, 3, 4, 6, 7, 8, 8, 9],则值 8 出现两次,数字 4 出现一次。你应该知道该方法有两个参数和一个返回值。代码有效,但我遇到的问题是,当我打印语句“值 x[i] 出现计数(x,x[i])次”时,它重复相同的语句,而它应该只打印每个值的语句.我需要帮助来制作它,所以它只会打印该语句,只要该值与它之前的值不同,如果它与它之前的值相同,代码应该跳过并移动到数组中的下一个值,直到它打印所有内容。

import java.util.Arrays;

public class Q7 {
    public static void main(String[] args) {
        int[] x = { 2, 3, 3, 3, 4, 6, 7, 8, 8, 9 };

        System.out.println(Arrays.toString(x));
        for (int i = 0; i < x.length; i++) {
        System.out.println("The value " + x[i] + " appears " + count(x, x[i]) + " times.");
        }
    }

    public static int count(int[] array, int target) {
        int counter = 0;
        for (int i = 0; i < array.length; i++) {
            if (array[i] == target) {
                counter++;
            }

        }
        return counter;
    }
}

Output:
[2, 3, 3, 3, 4, 6, 7, 8, 8, 9]
The value 2 appears 1 times.
The value 3 appears 3 times.
The value 3 appears 3 times.
The value 3 appears 3 times.
The value 4 appears 1 times.
The value 6 appears 1 times.
The value 7 appears 1 times.
The value 8 appears 2 times.
The value 8 appears 2 times.
The value 9 appears 1 times.

【问题讨论】:

  • 除非您被告知该数组将被排序,否则我建议您弄清楚如何对未排序的数组执行此操作。此外,排序不是必需的。

标签: java arrays eclipse


【解决方案1】:

在您的示例中(因为 数组已排序),您可以 改变

for (int i = 0; i &lt; x.length; i++)

for (int i = 0; i &lt; x.length; i = i + count(x, x[i]))

它会跳过重复的项目。

【讨论】:

  • 是的,现在可以使用了。谢谢,你是救命稻草。
  • @EzequielSolerPerez 尽情享受吧!不要忘记投票并接受最佳答案:)
【解决方案2】:

您必须以某种方式记住您已经为哪些值打印了消息。有几种方法可以做到这一点。例如,您可以对数组进行排序,并且仅当您在迭代时遇到您还没有的值时才输出消息。另一种简单的方法是将元素添加到集合中以获取数组的唯一值。带有集合的示例:

public static void main(String[] args) {
    int[] x = { 2, 3, 3, 3, 4, 6, 7, 8, 8, 9 };

    System.out.println(Arrays.toString(x));
    
    Set<Integer> set = new HashSet<>();
    for (int i = 0; i < x.length; i++) {
        if(set.add(x[i])){
            System.out.println("The value " + x[i] + " appears " + count(x, x[i]) + " times.");
        }
    }
}

【讨论】:

  • 使用集合的好答案。为什么不也纠正复数的答案。 +" time" + (count == 1 ? "" : "s") ; 它确实需要将计数提取到单独的变量中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多