如何在 Java 中仅使用 for 循环和 if 语句打印重复的值一次。

huangapple go评论61阅读模式
英文:

How to print duplicated value only once each using only for loop and if in java

问题

int[] numbers = {3, 2, 5, 11, 7, 10, 11, 3, 15, 11, 17, 10, 5};
int count = 0;
boolean dup = false;

System.out.println("数组的值:");
for (int n : numbers) {
    System.out.print(n + " ");
}

System.out.println("\n\n数组中重复的值:");
for (int a = 0; a < numbers.length; a++) {
    for (int b = a + 1; b < numbers.length; b++) {
        if (numbers[a] == numbers[b]) {
            count = numbers[a];
            dup = true;
        }
    }

    if (dup) {
        System.out.print(count + " ");
        dup = false;
        count = 0;
    }
}

要打印重复的值,但每个重复值只打印一次,您可以使用以下代码片段:

int[] numbers = {3, 2, 5, 11, 7, 10, 11, 3, 15, 11, 17, 10, 5};
boolean[] alreadyPrinted = new boolean[numbers.length];

System.out.println("数组的值:");
for (int n : numbers) {
    System.out.print(n + " ");
}

System.out.println("\n\n数组中重复的值:");
for (int a = 0; a < numbers.length; a++) {
    if (!alreadyPrinted[a]) {
        for (int b = a + 1; b < numbers.length; b++) {
            if (numbers[a] == numbers[b]) {
                alreadyPrinted[a] = true;
                alreadyPrinted[b] = true;
                System.out.print(numbers[a] + " ");
                break;
            }
        }
    }
}
英文:
	int[] numbers = {3, 2, 5, 11, 7, 10, 11, 3, 15, 11, 17, 10, 5};
	int count = 0;
	boolean dup = false;

	System.out.println(&quot;arrays value&quot;);
	for (int n : numbers ) {
		System.out.print(n +&quot; &quot;);
	}
	
	System.out.println(&quot;\n\nDuplicated value on arrays: &quot;);
	for (int a = 0 ; a &lt; numbers.length ; a++ ) {
		for (int b = a + 1 ; b &lt; numbers.length ; b++ ) {
			if (numbers[a] == numbers[b]) {
				count = numbers[a];
				dup = true;
			}
		}
		
		if (dup) {
			System.out.print(count +&quot; &quot;);
			dup = false;
			count = 0;
		}
	}

I want to print duplicated value only once each using only for loop and if

this output will print 3 5 11 10 11, how do I make only 3 5 11 10.

答案1

得分: 4

以下是翻译好的部分:

为此,使用数据结构set是明智的选择,它是一个不允许重复项的集合。这意味着无论您添加多少个相同值到set中,只会存储一个副本。现在您可以简单地编写:

Set<Integer> mySet = new HashSet<>(Arrays.asList(numbers));
for (int number : mySet) {
    System.out.println(number);
}

如果您只想打印重复的值,而不是只出现一次的值(您的问题不太清楚),您可以像这样做:

Set<Integer> mySet = new HashSet<>();
for (int number : numbers) {
    if (!mySet.add(number)) { // 如果e是重复项,即无法添加到set中,set方法add(e)将返回false
        System.out.print(duplicate + " ");
    }
}
英文:

For this it is smart to use the data structure set which is a collecion that do not allow duplicates. This means that whatever the number of same values you add to the set only one will be stored. Now you can simply write

Set&lt;Integer&gt; mySet = new HashSet&lt;&gt;(Arrays.asList(numbers));
for(int number : mySet) {
    System.out.println(number);
}

If you only want to print the values that are duplicates and not the values that only exist once (your question is not entirely clear) you may do something like this instead

Set&lt;Integer&gt; mySet = new HashSet&lt;&gt;();
for(int number : numbers) {
   if(!mySet.add(number)) { //the set method add(e) returns false if e is a duplicate i.e. can not be added to the set
      System.out.print(duplicate + &quot; &quot;);
   }
}

答案2

得分: 0

如果你想使用for循环

import java.util.ArrayList;

public class stackov {
    public static void main(String[] args) {
        int[] numbers = {3, 2, 5, 11, 7, 10, 11, 3, 15, 11, 17, 10, 5};
        int count = 0;
        boolean dup = false;

        System.out.println("数组的值");
        for (int n : numbers) {
            System.out.print(n + " ");
        }
        ArrayList<Integer> integers = new ArrayList<>();
        System.out.println("\n\n数组中重复的值:");
        for (int i : numbers) {
            if (!integers.contains(i)) {
                integers.add(i);
            }
        }

        for (int x : integers) {
            System.out.print(x + " ");
        }
    }
}
英文:

If you want with for loop

import java.util.ArrayList;

public class stackov {
    public static void main(String[] args) {
        int[] numbers = {3, 2, 5, 11, 7, 10, 11, 3, 15, 11, 17, 10, 5};
        int count = 0;
        boolean dup = false;

        System.out.println(&quot;arrays value&quot;);
        for (int n : numbers) {
            System.out.print(n + &quot; &quot;);
        }
        ArrayList&lt;Integer&gt; integers = new ArrayList&lt;&gt;();
        System.out.println(&quot;\n\nDuplicated value on arrays: &quot;);
        for (int i : numbers) {
            if (!integers.contains(i)) {
                integers.add(i);
            }
        }

        for (int x : integers) {
            System.out.print(x + &quot; &quot;);
        }
    }

}

答案3

得分: 0

假设您可以使用多个for循环和数据结构。

遍历值并在一个Map中累积每个值的出现次数。然后遍历Map,并输出计数大于1的值。

public static void main(String[] args) {
  int[] values = {......};
  Map<Integer, Integer> map = new HashMap<>();
  for (int value : values) {
    if (map.containsKey(value)) {
      map.put(value, 1 + map.get(value));
    } else {
      map.put(value, 1);
    }
  }
  for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    if (entry.getValue() > 1) {
      System.out.printf("值 %d 重复出现", entry.getKey());
    }
  }
}
英文:

I assume that you are allowed multiple for-loops and the use of data structures.

Iterate over the values and accumulate the count the occurrences of each value in a Map. Then iterate over the Map and output the values with a count > 1.

public static void main(String[]args) {
  int[] values = {...the values...};
  Map&lt;Integer,Integer&gt; map = new HashMap&lt;&gt;();
  for (int value : values) {
    if (map.containsKey(value)) {
      map.put(value, 1 + map.get(value));
    } else {
      map.put(value, 1);
    }
  }
  for (Map.Entry&lt;Integer,Integer&gt; entry : map.entrySet()) {
    if (entry.getValue() &gt; 1) {
      System.out.printf(&quot;Value %d was duplicated&quot;, value);
    }
  }
}

答案4

得分: -3

以下是翻译好的部分:

需要使用布尔数组标记已打印出的所有值而不只是一个单一的布尔值可以尝试以下代码

System.out.println("\n\n数组中的重复值:");
boolean[] dup = new boolean[1000];
for (int a = 0; a < numbers.length; a++) {
    if (dup[numbers[a]] == false) {
        System.out.print(numbers[a]);
        dup[numbers[a]] = true;
    }
}

如果您想要使用两个for循环速度较慢),那么您需要仅在当前索引之前检查重复值具有变量b的for循环应为`for (int b = 0; b < a; b++)`)

请注意,我已经按照您的要求将代码部分保持原样,未进行翻译。

英文:

You need to mark all values that have been printed out, using a boolean array (instead of just a single boolean). Try something like:

        System.out.println(&quot;\n\nDuplicated value on arrays: &quot;);
        boolean[] dup = new boolean[1000];
        for (int a = 0 ; a &lt; numbers.length ; a++ ) {
            if (dup[numbers[a]] == false) {
                System.out.print(numbers[a]);
                dup[numbers[a]] = true;
            }
        }

If you want to use 2 for loops (which is slower), then you need to only check for the duplicate value before this current index (the for with b should be for (int b = 0; b &lt; a; b++) )

huangapple
  • 本文由 发表于 2020年9月10日 18:17:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/63827554.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定