this is an array filter that returns 1 when the arguments are meet and 0 when they are not. for the arguments when 9 exists 11 must exist as well & when 7 exists in the array 13 must not exist.
my code returns 0 even though 9 and 11 exist and 7 exists but 13 doesn't exist. could someone please take a look at it?
public class Question4 {
private int [] array = {1,2,3,4,9,11,7};
private boolean condition1 = true;
private boolean condition2 = true;
public int isFilter() {
//condition 1 : (if list contains 9 then it must contain 11)
for (int i = 0; i < array.length; i ) {
if (array[i] == 9) {
for (int j = 0; j < array.length; j ) {
if (array[j] == 11) {
condition1 = true;
}
else {
condition1 = false;
}
}
}
}
//condition 2 : (if list contains 7 then it must not contain 13)
for (int k = 0; k < array.length; k ) {
if (array[k] == 7) {
for (int l = 0; l < array.length; l ) {
if (array[l] == 13) {
condition2 = false;
}
else {
condition2 = true;
}
}
}
}
//Evaluation and Return
if (condition1 == true && condition2 == true) {
return 1;
}
else {
return 0;
}
}
}
CodePudding user response:
Because this is homework, I’m going to answer broadly rather than with “code”.
Your main problem is your code is hard to read; your best first step is refactoring:
Create a method like this:
private static boolean contains(int[] array, int i) {
// write your own implementation here that returns true if array contains i
}
The use it to rewrite your conditions, eg:
if (contains(array, 7) && contains(array, 13)) {
// broken rule - do something
}
After doing that it should be easy to write and easy to read.
CodePudding user response:
Instead of
private boolean condition1 = true;
private boolean condition2 = true;
Use
private boolean condition1 = false;
private boolean condition2 = false;