Conditionals - boolean operators
Conditionals -- Boolean operations
- not
- and
- or
- de Morgan's laws
BooleanExamples.java
Deitel 5.9
Classwork
Create a project and in it a class with a main.
We will be using the Scanner class to read from the user. At the top of your
main class, after the package statement, paste
import java.util.Scanner;
Part A
☑
In your main method, paste this code. Scanner scan = new Scanner(System.in);
System.out.println("What is x?");
int x = scan.nextInt();
System.out.println("What is y?");
int y = scan.nextInt();
System.out.println("What is z?");
int z = scan.nextInt();
System.out.println("What is w?");
int w = scan.nextInt();
boolean happy;
boolean dead;
System.out.println("Are you happy (y/n)?");
String userhappy = scan.next();
System.out.println("Are you dead (y/n)?");
String userdead = scan.next();
☑ After this, if what they enter for userhappy is "y" set
happy to true, otherwise to false.
Do the same again to set a value for dead, so that we can better
serve our zombie users.
☑ Write single if statements using boolean operators to do as follows using the ints and booleans (not the strings):
- if x, y, and z all have the same value and the user is happy then print "Same and happy"
- if w is over 12 and the user is both happy and alive then print "Over 12, happy, alive"
- if x is less than z and both w and y are in the range between x and z print "in order"
- if either the user is happy and dead, or sad and alive
then print "happy zombie or emo friend"
Part B
☑ Add a new (different from part A) class with a main. In main, ask the user for a value for
each of three int variables x, y, and z.
☑
Using conditionals with logical operators, print the three ints back out in decreasing order. (If two numbers are the same,
it doesn't matter which order) (note this is different from the
previous EC, when you did not have logical operators)
So whether you were given 2, 1, 3, or 1,2,3 or 3,1,2, you'd print out 3, 2, 1.
You may add extra variables (i.e. small, med,
and large) if you wish, but that is NOT the only way to solve this.
(hint: think about how many possible combinations there are. There
is NO WAY to make the code shorter than just testing for all the
possible combinations. I promise. There is no trick to
shortening this. You must handle every possibility.)
Make sure you test all possible orders for the three numbers to check
your code works.