例如,我如何在不打印";2〃;再次使用环路
String[][] a={{"1","2"},{"2","3"}};
所需输出
1 2 3
String[][] matrix = { { "1", "2" }, { "2", "3" } };
Set<String> unique = new LinkedHashSet<>();
for (int row = 0; row < matrix.length; row++)
unique.addAll(Arrays.asList(matrix[row]));
System.out.println(String.join(" ", unique));
将上次打印的值存储在HashSet中,下次打印时检查HashSet是否已经存在,如果存在则不打印,否则打印
public static void main(String[] args) {
String[][] a = { { "1", "2" }, { "2", "3" } };
Set<String> set = new HashSet<String>();
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
String value = a[i][j];
if (!set.contains(value)) {
System.out.print(value + " ");
set.add(a[i][j]);
}
}
}
}
public static void main(String[] args) {
String[][] a={{"1","2"},{"2","3"}};
int number = 0;
for(int i=0; i<a.length; i++) {
//System.out.println(a[i]);
for(int p=0; p<a[i].length; p++) {
if(a[i][p].equals("2")) {
number++;
}
if(number == 1) { //Use this to allow how many times you want to print number 2 in this case
break;
}
System.out.println(a[i][p]);
}
}
}