如果給定數組調用x(由用戶在另一個方法中輸入)包含重複值,我試圖讓方法(duplicateates)返回true。否則,它將返回false。而不是檢查整個數組,它被初始化爲100,它將只檢查輸入值的數量,這個數值用一個全局計數器跟蹤:numElementsInX。Java,如果數組包含重複值,則返回true
完成此操作的最佳方法是什麼?
public static boolean duplicates (int [] x)
我提示用戶數據,像這樣:
public static void readData (int [] x, int i){
Scanner input = new Scanner(System.in);
System.out.println("Please enter integers, enter -999 to stop");
while (i <= 99) {
int temp = input.nextInt();
if(temp == -999){
break;
}
else {
x[i++]=temp;
}
// else
}//end while
printArray(x,i);
}//end readData
public static void printArray(int [] x, int numElementsInX){
int n = numElementsInX;
for (int i = 0; i < n; i++){
System.out.print(x[i] + " ");
}//end for
System.out.println();
}//end printArray
我肯定有一個更好的方式來做到這一點,但是這是怎麼了,我一直至今任教。
你的意思是'numElementsInX'是那裏的元素的數量*如果在'x'中,如果沒有重複的話會是*的數量? – david
編輯:對不起,這是一個全球計數器。不,它是數組中輸入值的數量。用戶最多可以輸入100個值。返回array.length給出了整個初始化數組,而不是隻輸入正確的值? – andrsnn