Reputation: 79
I am writing an algorithm that returns true if three elements from a list a are able to sum up to three. Each element in a list can be repeated, so whenever there is a 0, I will have true. My question is not on the algorithm, albeit I do need a revision (an extra constraint) on the second if statement for this algorithm to be complete. After reading the responses, I have revised my code to just return. Now there is an output of nothing from my code, but I believe it is because I need to adjust my second condition.
public class main {
public static void main(String args[]) {
int[] a = { -6, 2, 4 }; // true -6, 2, 4
// int [] a = {-6, 2, 5}; false
// int [] a = {-6, 3, 10, 200}; true -6, 3, 3
// int [] a = {8, 2, -1, 15}; true 2, -1, -1
// int [] a = {8, 2, -1, -1, 15}; true 2, -1, -1
// int [] a = {5, 1, 0, 3, 6}; true 0, 0, 0
sum(a);
}
public static boolean sum(int[] a) {
int x = 0;
int len = a.length;
boolean check = false;
while (x < len) {
if (a[x] == 0) {
check = true;
if (check == true)
{System.out.println("break time yo@");
break;}
}
if (a[x] + a[x + 1] + a[x + 2] == 0 ) {
check = true;
if (check == true)
{break;}
}
for (int i = 0; i <= len; i++) {
if ((i == 2 * a[x]) || (2 * i == a[x])) {
check = true;
if (check == true)
{break;}
}
}
x += 1;
}
return check;
}
}
Upvotes: 1
Views: 505
Reputation: 7434
Replace sum(a) with System.out.println(sum(a)); and you should get true or false printed in console.
Upvotes: 1
Reputation: 4111
For your problem, you don't even need a check
variable. Just call return true;
when required... and return false;
after your while loop
Upvotes: 2
Reputation: 8338
You don't have to break for this sort of thing. Just replace your breaks with
return true;
When you return
in Java, the code stops executing - it won't continue to run the result of your algorithm.
Just to give you an example, look at a method like this:
public boolean numberCheck(int number) {
if(number == 20) {
return true;
}
return false;
}
If the number is equal to 20, the method will return true
and then stop - it won't go on to return false
, because once the return is called, the execution effectively stops.
Upvotes: 3