int[] numbers = {3, 2, 5, 11, 7, 10, 11, 3, 15, 11, 17, 10, 5};
int count = 0;
boolean dup = false;
System.out.println("arrays value");
for (int n : numbers ) {
System.out.print(n +" ");
}
System.out.println("\n\nDuplicated value on arrays: ");
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;
}
}
我只想使用for循环和if,只打印一次重复的值
此输出将打印3 5 11 10 11,我怎么只打印3 5 11 10。
答案 0 :(得分:3)
为此,明智的做法是使用数据结构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)) { //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 + " ");
}
}
答案 1 :(得分: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("arrays value");
for (int n : numbers) {
System.out.print(n + " ");
}
ArrayList<Integer> integers = new ArrayList<>();
System.out.println("\n\nDuplicated value on arrays: ");
for (int i : numbers) {
if (!integers.contains(i)) {
integers.add(i);
}
}
for (int x : integers) {
System.out.print(x + " ");
}
}
}
答案 2 :(得分:0)
我假设允许您使用多个for循环和使用数据结构。
遍历这些值,并累加Map中每个值的出现次数。然后遍历Map并输出count> 1的值。
public static void main(String[]args) {
int[] values = {...the 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("Value %d was duplicated", value);
}
}
}
答案 3 :(得分:-3)
您需要使用布尔数组(而不是单个布尔值)标记所有已打印出的值。尝试类似的东西:
System.out.println("\n\nDuplicated value on arrays: ");
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;
}
}
如果要使用2个循环(速度较慢),则只需要在当前索引之前检查重复值(b的for应该为for (int b = 0; b < a; b++)
)