public class Exercise1 {
//Notice that in this main, each of the functions have been called for you
public static void main(String[] args) {
int[] data = {1,3,5,4,7,9,1,3};
int[] output = new int[data.length];
System.out.println("Does our array contain a '1':"+ contains(data, 1)); //true
System.out.println("Does our array contain a '0':"+ contains(data, 0)); //false
System.out.println("What is the index of '4'? " + indexOf(data, 4)); //3
System.out.println("The number of occurrences of '1'? " + count(data, 1)); //2
duplicates(data, output);
System.out.println("After removing duplicates from data:");
System.out.println(Arrays.toString(output));
}
public static boolean contains(int[] input, int target) {
//todo: see lab
for (int i = 0; i < input.length; i++) {
if (target == input[i])
return true;
}
return false;
}
public static int indexOf(int[] input, int target) {
//todo: only find the indexOf a target if we contain() it
if (contains(input, target) == false) {
return -1;
}
for (int i = 0; i < input.length; i++) {
if (target == input[i]) {
return i;
}
}
return -1;
}
public static int count(int[] input, int target){
int retVal = 0;
//todo: only try to count a number that we contain()
if (contains(input, target) == true) {
for (int i = 0; i < input.length; i++) {
if (input[i] == target) {
retVal++;
}
else {
retVal = retVal;
}
}
}
return retVal;
}
public static void duplicates(int[] input, int[] output) {
//todo: Transfer items once from the arrays:input and output.
//transfer items from input to the output array IF:
//only if newArray.count(target) == 0 //ie, we haven't put this in yet
//only if newArray.indexOf(target) == -1 //not found in newArray, or
//only if newArray.contains(target) == false //does not exist in the new array
}
我已經得到所有的我的方法除了重複一個工作 - 我不得不從陣列刪除重複在主所以應該輸出{1,3,5,4, 7,9,0,0}。爲此,我們應該調用count()方法,但如果參數不同,我不知道如何重複調用該方法。誰能幫忙?
你所說的 「如果參數不同」 是什麼意思?你試過什麼了? – sinclair
例如,在indexOf中,我調用了contains,因爲它們都具有相同的參數(輸入和目標),但如果我嘗試調用重複計數,則它不起作用,因爲變量目標未在重複中使用。 –