我正在做一個HW作業,要求寫一個名為count的方法,確定一個目標值在陣列中出現的次數。例如,如果你的陣列是[2, 3, 3, 3, 4, 6, 7, 8, 8, 9],值8出現兩次,數字4出現一次。你應該知道,這個方法有兩個引數和一個回傳值。代碼可以作業,但我遇到的問題是,當我列印 "值x[i]出現了count(x,x[i])次 "的陳述句時,它重復了同一陳述句,而它應該只為每個值列印陳述句。我需要幫助,以使它只列印陳述句,只要該值與之前的值不同,如果它與之前的值相同,代碼應跳過并轉向陣列中的下一個值,直到它列印出所有內容。
import java.util.Arrays。
public class Q7 {
public static void main(String[] args){
int[] x = { 2, 3, 3, 3, 4, 6, 7, 8, 8, 9 };
System.out.println(Arrays.toString(x))。
for (int i = 0; i < x.length; i ) {
System.out.println("值" x[i] " 出現" count(x, x[i]) " 次。")。
}
}
public static int count(int[] array, int target) {
int counter = 0;
for (int i = 0; i < array.length; i ) {
if (array[i] == target) {
counter ;
}
}
return counter;
}
}
輸出。
[2, 3, 3, 4, 6, 7, 8, 8, 9]
值2出現1次。
值3出現3次。
值3出現3次。
值3出現3次。
值4出現1次。
值6出現1次。
值7出現1次。
值8出現2次。
值8出現2次。
值9出現1次。
uj5u.com熱心網友回復:
在你的例子中(因為陣列是排序的),你可以直接 改變
for (int i = 0; i < x.length; i )
改為
for (int i = 0; i < x.length; i = i count(x, x[i]))
它將跳過重復的專案。
uj5u.com熱心網友回復:
你必須以某種方式記住你已經為哪些值列印了資訊。有幾種方法可以做到這一點。例如,你可以對你的陣列進行排序,如果你在迭代時遇到一個你還沒有的值,才輸出訊息。另一種簡單的方法是將元素添加到一個集合中以獲得陣列的唯一值。用一個集合的例子:
public static void main(String[] args) {
int[] x = { 2, 3, 3, 3, 4, 6, 7, 8, 8, 9 };
System.out.println(Arrays.toString(x))。
Set<Integer> set = new HashSet<>()。
for (int i = 0; i < x.length; i ) {
if(set.add(x[i]) ){
System.out.println("值" x[i] " 出現" count(x, x[i]) " 次。")。
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/308370.html
標籤:
上一篇:帶有定時器的Python執行緒-TypeError:'NoneType'物件不可呼叫
下一篇:對控制反轉和依賴注入的突然頓悟
