2014-04-23 34 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; 
相关问题