Reputation: 902
Although I have already add "return true" & "return false" at the "boolean Method", but I keep getting error "add return". Does anybody know what the problem is?
The question is: "Given an unsorted array that may contain duplicates. Also given a number k which is smaller than size of array. Write a function that returns true if array contains duplicates within k distance."
public static void main (String[] args){
int[] arr = {2, 5, 7, 4, 2, 7, 8, 5, 4, 9};
int k = 3;
System.out.println(duplicateKDistance(arr, k));
}
public static boolean duplicateKDistance(int[] array, int m){
for (int i=0; i<array.length; i++){
for(int j=i+1; j<=m; ){ // if you add "j++", it will be dead code here :)
if (array[i] == array[j])
return true;
else
return false;
}
}
}
}
Upvotes: 1
Views: 175
Reputation: 84
You need to add the return outside of the For loop. The way you have it setup at the moment your entire program assumes you enter the loop. If you never enter that For loop the program will never have a return. So Java wants you to place the return false outside of the first for loop. You should probably take out that else return false.... as it will always trigger if your if statement is not true. By having the return false outside the loop your logic behind why you need the else is now captured and implied by you not entering into the if statement within your second for loop.
public static boolean duplicateKDistance(int[] array, int m){
for (int i=0; i<array.length; i++){
for(int j=i+1; j<=m; j++){
if (array[i] == array[j])
return true;
}
}
return false;
}
Upvotes: 1
Reputation: 2324
You need to change logic try following code
public static void main(String[] args) {
int[] arr = { 2, 5, 7, 4, 2, 7, 8, 5, 4, 9 };
int k = 3;
System.out.println(FindZero.duplicateKDistance(arr, k));
}
public static boolean duplicateKDistance(int[] array, int m) {
boolean flag = false;
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j <= m;) { // if you add "j++", it will be dead
// code here :)
if (array[i] == array[j]) {
flag = true;
break;
}
}
}
return flag;
}
Upvotes: 1
Reputation: 3688
you only return a value if you ever enter any of the loops.
If none of the loop conditions are never met, you'll never reach a return
statement. Simply add one at the end of the method:
public static boolean duplicateKDistance(int[] array, int m){
for (int i=0; i<array.length; i++){
for(int j=i+1; j<=m; ){ // if you add "j++", it will be dead code here :)
if (array[i] == array[j])
return true;
else
return false;
}
}
return false;
}
Upvotes: 0