Why is this not returning true? - java

public void check() {
if (particle < 0) {
if (point[3].equals(point[3]) == true) {
check = true;
}
check = false;
}
}
Shouldn't point[3] be equal to itself? making it true?

Maybe you mean to say else check = false?
public void check(){
if(particle < 0){
if(point[3].equals(point[3]) == true){
check = true;
}else{
check = false;
}
}
//here it is true
}
or simply:
public void check(){
if(particle < 0){
check = point[3].equals(point[3]);
}
//here it is true
}

You must return after check = true; from the function, or use else. Else it will fall down from the if and return false always
if (...) {
check = true;
}
else {
check = false;
}
public void check(){
if(particle < 0){
if(point[3].equals(point[3]) == true){
check = true;
}else{
check = false;
}
}
}

Try this:
public boolean check() {
if (particle < 0) {
return point[3].equals(point[3]);
} else {
return false;
}
}

what about particle?
by convention point ought to be equal to itself, but you could always implement it otherwise.
but of course, the other reply is correct, this function will always end with check=false

Related

Why do I get a missing return statement error although there is a return statement in each of my if and if else blocks?

What I am trying to do here out of flower1 and flower2, one is even and one is odd then return true.
If both are even, return false.
If both are odd, return false.
When my code is:
public class OppositesAttract {
public static boolean isLove(final int flower1, final int flower2) {
if(flower1%2==0 && flower2%2==0){
return false;
}else
if(flower1%2!=0 && flower2%2!=0){
return false;
} else
if(flower1%2==0 || flower2%2==0){
return true;
}
}
}
I get a "missing return statement" error.
So I added:
public class OppositesAttract {
public static boolean isLove(final int flower1, final int flower2) {
if(flower1%2==0 && flower2%2==0){
return false;
}else
if(flower1%2!=0 && flower2%2!=0){
return false;
} else
if(flower1%2==0 || flower2%2==0){
return true;
}else{
return true;
}
}
}
Now, the code works but I do not understand why I have to add the additional return statement.
The compiler doesn't know the first 3 terms cover all situations.
if(flower1%2==0 && flower2%2==0){
return false;
} else if(flower1%2!=0 && flower2%2!=0){
return false;
} else if(flower1%2==0 || flower2%2==0){
return true;
}
to you this reads as: all options are covered. but the compiler just sees:
if (somethingThatMayBeTrue) {
} else if (somethingElseThatMayBeTrue) {
} else if (aThirdThingThatMayBeTrue) {
} .... and what if none of them are?
You may know that the last else if should always be true (since you know they are not both uneven) but the compiler doesn't generally try to understand your code.
in your case, the last clause (aThirdThingThatMayBeTrue, flower1%2==0 || flower2%2==0) is actually (somethingThatIsAlwaysTrueIfPreviousTermsAreFalse).
so you can treat it as such:
if(flower1%2==0 && flower2%2==0){
return false;
} else if(flower1%2!=0 && flower2%2!=0){
return false;
} else {
return true;
}

Printing datastructure from input doesn't work

I'm trying to create a program which prints a datastructure from the input. The input and output looks like this: http://puu.sh/kDMc9/2d46462d4d.png. So for example, in the first test case: the first line indicates how many lines will follow in that case. Then if it's the number 1 as the first number on a line it means that you want to add elements to stack/queue/priority-queue and 2 means you want to take out an element, so the second number on a line is the value. Then the output prints if it's stack,queue, priority-queue, impossible or not sure(can be more than one)
This is the code I have now:
import java.util.PriorityQueue;
import java.util.Scanner;
public class DataStructure {
public static void main(String[] args)
{
while(calculate());
}
private static boolean calculate()
{
Scanner input = new Scanner(System.in);
int numberOfRowsPerCase = input.nextInt();
Stack<Integer> stack = new Stack<Integer>();
Queue<Integer> queue = new Queue<Integer>();
PriorityQueue<Integer> prioQueue = new PriorityQueue<Integer>();
boolean stackBool = true;
boolean queueBool = true;
boolean prioQueueBool = true;
int next;
for(int i = 0; i < numberOfRowsPerCase; i++)
{
next = input.nextInt();
if(next == 1)
{
next = input.nextInt();
stack.push(next);
queue.enqueue(next);
prioQueue.add(next);
}
else if(next == 2)
{
next = input.nextInt();
if(!stack.pop().equals(next))
{
stackBool = false;
}
else if(!queue.dequeue().equals(next))
{
queueBool = false;
}
else if(!prioQueue.poll().equals(next))
{
prioQueueBool = false;
}
}
if(stackBool == true)
{
System.out.println("stack");
}
else if(queueBool == true)
{
System.out.println("queue");
}
else if(prioQueueBool == true)
{
System.out.println("priority queue");
}
else if((stackBool == true && queueBool == true) || (queueBool == true && prioQueueBool == true) || (stackBool == true && prioQueueBool == true))
{
System.out.println("not sure");
}
else
{
System.out.println("impossible");
}
}
//Check EOF
String in;
in = input.nextLine();
in = input.nextLine();
if(in.equals(""))
{
return false;
}
return true;
}
}
But when I run the test-case on the picture above, my program prints this: https://ideone.com/mIO1bs which is wrong. I can't find why it does that, can anyone else here maybe see?
Assuming that your logic setting the boolean flags is correct then this part
if(stackBool == true)
{
System.out.println("stack");
}
...
else if((stackBool == true && queueBool == true) || (queueBool == true && prioQueueBool == true) || (stackBool == true && prioQueueBool == true))
{
System.out.println("not sure");
}
will never work as intended because parts of the second condition were already caught by the first condition.
The better suggestion is to come up with a clearer way of representing this. A suggestion that will still probably work is to put your more complicated if statements at the start of the if-else chain.
Disregarding above assumption:
if(!stack.pop().equals(next))
{
stackBool = false;
}
else if(!queue.dequeue().equals(next))
{
queueBool = false;
}
else if(!prioQueue.poll().equals(next))
{
prioQueueBool = false;
}
These should not be elses, they're all completely independent.

Check that every if has a matching endif

I recently had to code up an interpreter for Bitcoin's script language; part of this involved coming up with an algorithm to check that the control flow in a given script made sense (i.e. every OP_IF had a matching OP_ENDIF, every OP_ELSE and OP_ENDIF had a matching OP_IF, etc.).
This is what I came up with:
public class if_else_checker {
public static boolean search(String[] commands, String[] tracker, int if_index) {
boolean seenElse = false;
for (int i = if_index; i < commands.length; i++) {
if (commands[i].equals("OP_ELSE")) {
if (seenElse == true && tracker[i] == null) return false;
if (tracker[i] == null) {
tracker[i] = "OP_ELSE";
seenElse = true;
}
}
else if (commands[i].equals("OP_ENDIF")) {
if (tracker[i] != null && tracker[i].equals("OP_ENDIF"))
{
continue;
}
tracker[i] = "OP_ENDIF";
return true;
}
else if (commands[i].equals("OP_IF")) {
if (tracker[i] != null && tracker[i].equals("OP_IF")) {
continue;
}
tracker[i] = "OP_IF";
if (search(commands, tracker, i + 1) == false) return false;
}
}
return false;
}
public static boolean validate(String[] args)
{
String[] tracker = new String[args.length];
for (int i = 0; i < args.length; i++)
{
if (args[i].equals("OP_IF"))
{
if (tracker[i] == null || !tracker[i].equals("OP_IF"))
{
tracker[i] = "OP_IF";
if (search(args, tracker, i + 1) == false) return false;
}
else continue;
}
else if (args[i].equals("OP_ELSE"))
{
if (tracker[i] == null || !tracker[i].equals("OP_ELSE")) return false;
}
else if (args[i].equals("OP_ENDIF"))
{
if (tracker[i] == null || !tracker[i].equals("OP_ENDIF")) return false;
}
}
return true;
}
public static void main(String[] args)
{
System.out.println(validate(args));
}
}
It works, but I was wondering if there is a way to optimise it/if there is a standard way of doing this? (One optimisation is to have validate() return the index of the OP_ENDIF it finds, rather than a boolean; this would change runtime from quadratic-time to linear).
The best way of solving this is by using a Stack data structure. Every new opening instruction (e.g. OP_IF) is pushed into the stack. When you find a closing instruction (e.g. OP_ENDIF), you pop the top element of the stack and check if it is the corresponding opening instruction for that closing instruction. If so, then it's valid, and you proceed to the next step. In the end, if the stack is empty then the control flow you're checking is correct. Otherwise, it's not.

Booleans and returns

public boolean percentDepreciatedOutOfRange() {
if (percentDepreciated < DEPRECIATION_MIN || percentDepreciated > DEPRECIATION_MAX) {
return true;
}
else {
return false;
}
}
Can the code above be written without the else statement and just have return false; after the if statement and still have the same result? If so, why? This is what I mean
public boolean percentDepreciatedOutOfRange() {
if (percentDepreciated < DEPRECIATION_MIN || percentDepreciated > DEPRECIATION_MAX) {
return true;
}
return false;
}
You should just write
public boolean percentDepreciatedOutOfRange() {
return percentDepreciated < DEPRECIATION_MIN || percentDepreciated > DEPRECIATION_MAX);
}
which is more readable. Avoid statements like
If (xxx) { return true; }
else { return false; }
because the if just adds noise around the expression.
The reason why this is legal is that the boolean type is the same in evaluating the if expression and in the return type of the method.
Because return actually exits the function (method).
In the case the if is not entered the rest of the code will execute normally.
Since you have boolean returns, having return false at the end of the function, means everything up to the end failed.
You could even rewrite it to:
public boolean percentDepreciatedOutOfRange() {
if (percentDepreciated < DEPRECIATION_MIN) {
return true;
}
if (percentDepreciated > DEPRECIATION_MAX) {
return true;
}
return false;
}
To clearly state the tests in the method.
Another way I like:
Defining return variable as 1st statement with default value.
Change the variable in method in various biz logic
Return the variable value (Single return statement)
public boolean percentDepreciatedOutOfRange() {
boolean status = false;
status = percentDepreciated < DEPRECIATION_MIN || percentDepreciated > DEPRECIATION_MAX;
return status;
}

if and else statement

I'm trying to implement a toString method, and the output of the toString depends on the boolean variables. Below is my class and main.
public class Cell {
public int addSpaces;
boolean isEmpty;
boolean isChute;
boolean isLadder;
public Cell() {
addSpaces = 10; //I initialized addSpaces to 10 for testing purpose
}
public boolean isChute() { //first boolean method
if (addSpaces == -10) {
return true;
} else {
return false;
}
}
public boolean isLadder() {//second boolean method
if (addSpaces == 10) {
return true;
} else {
return false;
}
}
public boolean isEmpty() { //third boolean method
if (addSpaces == 0) {
return true;
} else {
return false;
}
}
public String toString() {
String print;
if (isChute = true) //if isChute is true return true.
{
print = "C10"; // toString output = "C10"
} else if (isLadder = true) // if isLadder is true return true
{
print = "L10"; // toString output == "L10"
} else {
print = "---"; // else toString print output = "---"
}
return print;
}
public static void main(String[] arg) {
Cell s = new Cell();
System.out.println(s.addSpaces);
System.out.println(s);
}
}
Regardless of the input state of toString, I basically get the same output "C10".
Can someone tell me what I did wrong?
I'm new to this website so I appreciate any feedback for future reference. Thank you.
You've fallen into one of the languages "gotchas"
This...
if(isChute = true) //if isChute is true return true.
print = "C10"; // toString output = "C10"
else if (isLadder = true) // if isLadder is true return true
print = "L10"; // toString output == "L10"
else
print = "---"
is actually assigning true to isChute. You should be using == not =
Updated
A better approach would be...
if(isChute) //if isChute is true return true.
print = "C10"; // toString output = "C10"
else if (isLadder) // if isLadder is true return true
print = "L10"; // toString output == "L10"
else
print = "---"
If there are only two states that the object can be (either a chute or ladder), you could simply use
if(isChute) //if isChute is true return true.
print = "C10"; // toString output = "C10"
else print = "L10"; // toString output == "L10"
If it can have more then 2 states then I would use an enum type instead.
isChute is assigned to true. So "C10" is being returned all the time by toString().
Change it
if(isChute){
...
}else if(isLadder){
...
}else{
..
}

Categories