[英]Get indexes of 2 duplicated elements in 2d array of INTs JAVA
我需要專家的幫助。 我有一項任務要在二維數組中查找 2 個重復元素並打印出它們的索引。 這是我制作的代碼。 它創建一個二維數組,然后從鍵盤手動填充它。 但是現在我在查找和打印重復項的方法上遇到了一些問題。 如果沒有重復,則打印 FALSE,如果有,則打印 TRUE。 但我不能讓它打印出所有的重復項及其索引。 請幫我解決一下這個。 此致
import java.io.*;
import java.util.HashSet;
import java.util.Set;
import static java.lang.System.out;
public class Main {
public static void main(String[] args)
throws NumberFormatException, IOException {
BufferedReader reader = new BufferedReader
(new InputStreamReader (System.in));
out.println("Введите размерность массива n:");
int n = Integer.parseInt(reader.readLine());
out.println("Введите размерность массива m:");
int m = Integer.parseInt(reader.readLine());
int [][] a = new int [n][m];
out.println("Введите числа массива :");
int i,j;
for (i = 0; i < a.length; i++) {
for (j = 0; j < a[i].length; j++) {
a[i][j] = Integer.parseInt(reader.readLine());
}
}
out.println("Введенный массив : ");
for (i = 0; i < a.length; i++, out.println()) {
for (j = 0; j < a[i].length; j++) {
out.printf(" %4d", a[i][j]);
}
}
out.println(extra(a));
}
private static boolean extra(int[][] data) {
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
if (set.contains(data[i][j])) {
out.printf("[%d][%d] - %d\n", i, j, data[i][j]);
return true;
} else {
set.add(data[i][j]);
}
}
}
return false;
}
}
確定集合中的任何項目是否滿足條件,同時還處理每個項目的一般方法是:
boolean conditionSatisfied = false;
for each item in collection {
if item satisfies condition {
process item;
conditionSatisfied = true;
}
}
return conditionSatisfied;
我改變了你的方法並使用了一個發現的布爾變量..這會起作用
private static boolean extra(int[][] data) {
boolean found = false;
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
if (set.contains(data[i][j])) {
out.printf("[%d][%d] - %d\n", i, j, data[i][j]);
found = true;
} else {
set.add(data[i][j]);
}
}
}
return found;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.