2014-04-23 47 views
-1

我需要專家的幫助。我有一個任務在2d數組中找到2個重複元素並打印出索引。這是我製作的代碼。它創建一個2d數組,然後從鍵盤手動填充它。但是現在我發現和打印重複的方法有一些問題。如果沒有重複,它將打印FALSE,如果有一些則爲TRUE。但是我無法打印出所有的副本和索引。請幫我解決一下這個。最好的問候在INT的2d數組中獲取2個重複元素的索引JAVA

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; 
    } 


} 
+3

只要找到第一個副本,「返回true」就會返回。您如何看待這會影響您查找所有重複項的能力? –

回答

0

我改變你的方法,並用於發現一個布爾變量。 。這將起作用

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; 
} 
+0

嗯..有時我們需要給魚,但有時我們也需要給釣魚杆..也許,你見過@ Jason的回答? –

1

用於確定集合中的任何項目滿足條件,同時還處理每一個項目,是一個普遍的方法:

boolean conditionSatisfied = false; 

for each item in collection { 
    if item satisfies condition { 
     process item; 
     conditionSatisfied = true; 
    } 
} 

return conditionSatisfied; 
相關問題