![](/img/trans.png)
[英]java: comparing value of 2D-array with value of arraylist at the same column
[英]Number of times a value occurs in each column of a 2d-array in Java?
ArrayList<Integer> newArray = new ArrayList<>();
for (int i =0; i < count; i++) {
newArray.add(i);
}
for (int j = 0; j <= 3; j++) {
Collections.shuffle(newArray);
System.out.println(newArray.toString());
}
//Let count equal 4 since we want a square
int[][] counters = new int[count][count];
int numAppear = 0;
int row = 0;
int col = 0;
for (row = 0; row < count; row++) {
for (col = 0; col < count; col++) {
if (newArray.get(row).equals(newArray.get(col))) {
numAppear++;
}
counters[row][col] = numAppear;
System.out.print(counters[row][col]+" ");
}
System.out.println();
}
在代碼中,我想查找如果我訪問第i行的第j列有多少次,那么我會在ArrayList的索引j中出現所有的隨機播放。
另外,我正在嘗試打印計數器數組,但是盡管嘗試了.toString以及Arrays.toString,但我得到了內存哈希。
假設這是我對混洗數組的輸出:
[3, 1, 2, 0]
[2, 0, 1, 3]
[1, 3, 2, 0]
[0, 1, 2, 3]
現在輸出counters [row] [col] = numAppear; 應該看起來像這樣:第一行:因為row0 =改組數組的col0,numAppear = 1。
第三行在(2,2)中有一個2,因為在(2,2)的隨機數組中,#2在同一列中出現兩次,但在前幾行中
[1, 1, 1, 1]
[1, 1, 1, 1]
[1, 1, 2, 2]
[1, 2, 3, 2]
為什么使用“ counters [row] [col] = numAppear;” ?
如果只是為了最終計數,請在開始遍歷元素之前初始化另一個int計數器。
由於“ numAppear”值在兩次匹配之間仍然存在,因此在將臨時 “ numAppear”值添加到數組時看不到該值。 如果我了解您的打印聲明的目標,那么這可能是一個可行的選擇:
System.out.println(“在“ +行+”行和“ + col列”找到匹配項;
編輯:至於打印比賽,我從一開始就初始化了一個數組列表,並在最后進行遍歷。 例如:
ArrayList<String> matchList = new ArrayList<String>();
要添加到它:
matchList.add(numAppear);//or whatever you're trying to add
然后最后:
for (String s : matchList){
System.out.println("Match at: " + s);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.