![](/img/trans.png)
[英]Counting the number of times an element occurs in a given column for a 2D array?
[英]Counting number of times an int occurs in an array (Java)
我想要的OCCURENCES數量計數int
S,一到六個包容性,在大小6我想與一個int出現在每個指標的次數返回數組的數組,但有一個索引零。
例:
輸入 : [3,2,1,4,5,1,3]
預期產出 : [2,1,2,1,1,0]
。
問題:
它輸出[1,1,3,0,1,0]
,代碼摘錄如下。 我怎樣才能解決這個問題? 我找不到我錯的地方。
public static int arrayCount(int[] array, int item) {
int amt = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == item) {
amt++;
}
}
return amt;
}
public int[] countNumOfEachScore(){
int[] scores = new int[6];
int[] counts = new int[6];
for (int i = 0; i < 6; i++){
scores[i] = dice[i].getValue();
}
for (int j = 0; j < 6; j++){
counts[j] = arrayCount(scores, j+1);
}
return counts;
}
dice []只是一個Die對象數組,它有一個方法getValue(),它返回一個介於1和6之間的int,包括1和6。 counts []是內容錯誤的int數組。
編寫另一個代碼而不是調試你的代碼會更快。
public static int[] count(int[] array) {
int[] result = new int[6];
for (int i = 0; i < array.length; i++) {
try{
result[array[i]-1]++;
} catch (IndexOutOfBoundsException e) {
throw new IllegalArgumentException("The numbers must be between 1 and 6. Was " + String.valueOf(array[i]));
}
}
return result;
}
以上將導致6個int
的數組。 i
TH結果陣列中的數量將存儲的出現次數的數目i+1
。
public static void main(String [] args){
int []ar=new int[]{3,2,1,4,5,1,3};
System.out.println(Arrays.toString(counter(ar)));
}
public static int[] counter(int []ar){
int []result=new int [6];
for(int i=0;i<ar.length;i++){
int c=0;
for(int j=0;j<ar.length;j++){
if(j<i && ar[i]==ar[j])
break;
if(ar[i]==ar[j])
c++;
if(j==ar.length-1){
result[i]=c;
}
}
}
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.