Java Programming Boolean if-else statement

  • Context: Java 
  • Thread starter Thread starter dellmac
  • Start date Start date
  • Tags Tags
    Java Programming
Click For Summary
SUMMARY

The forum discussion centers on correcting a Java if-else statement related to boolean logic. The original code incorrectly uses the negation operator "!" leading to incorrect outputs. The recommended solution involves first checking if both booleans, isBalloon and isRed, are true to print "Red balloon", simplifying the logic and eliminating unnecessary negations. This adjustment ensures the correct outputs are printed based on the boolean values.

PREREQUISITES
  • Understanding of Java programming syntax
  • Familiarity with boolean data types and logical operators
  • Knowledge of control flow statements in Java
  • Basic debugging skills in Java
NEXT STEPS
  • Learn about Java boolean expressions and their evaluation
  • Explore Java control flow statements, focusing on if-else structures
  • Study the use of logical operators in Java, including AND, OR, and NOT
  • Practice debugging Java code to identify and fix logical errors
USEFUL FOR

Java developers, programming students, and anyone looking to improve their understanding of boolean logic and control flow in Java programming.

dellmac
Messages
4
Reaction score
0
Looking for some assistance with this. I've been messing with this for hours and can't seem to get it right. Some assistance would be greatly appreciated. What I have below is not correct. Material in green cannot be changed. Thanks!Print "Balloon" if isBalloon is true and isRed is false. Print "Red balloon" if isBalloon and isRed are both true. Print "Not a balloon" otherwise. End with newline.import java.util.Scanner;

public class RedBalloon {
public static void main (String [] args) {
boolean isRed = false;
boolean isBalloon = false;

if (!isBalloon || isRed) {
System.out.println("Balloon");
}

else if (!isBalloon && !isRed) {
System.out.println("Red balloon");
}

else {
System.out.println("Not a balloon");
}

return;
}
}
 
Technology news on Phys.org
Hi,

The logical operator "!" is a negation in Java, so you are doing just the opposite you are asked for.

The boolean "!isBalloon" is true if "isBalloon" is false, and vice versa.

My recommendation, check first whether the two booleans are true and print "Red ballon", in this way you will only need to check one boolean in the next if condition, I think that way is easier (Just eliminating one logical operator).
 
Alright thank you! Your response gave me a great understanding, and I have it now. Really appreciate the assistance!
 

Similar threads

  • · Replies 7 ·
Replies
7
Views
11K
Replies
8
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 14 ·
Replies
14
Views
6K
Replies
2
Views
51K
  • · Replies 13 ·
Replies
13
Views
4K
  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 2 ·
Replies
2
Views
13K