Conditionals - nesting if/else
Conditionals - Nesting / toString
- nested if
- if-else-if
- if in toString
IfExamples.java
Condition.java
Bunny.java.
Deitel 4.1-4.7
Classwork
reminder: please only use things we have covered to this point, even
if you happen to already know about things like boolean operators.
Part A
In your project, create a class with a main method, TestCollectors.
Paste the following code into your main. It was written by someone
who doesn't understand if and else. Fix this code to do the same
thing, but using if and else correctly.int x = 5; // code should work for any value of x
int y = 10; // code should work for any value of y
if (x < y) {
System.out.println("x is small");
} else if (! (x < y)) {
if (x == y) {
System.out.println("they are same");
} else if (x != y) {
if (x > y) {
System.out.println("x is big");
}
}
Part B
☑
Add new class, Collector, which has an int instance variable
collected, to keep track of how many of something they collected,
another int available, for how many of that thing exist, and a boolean
completist, which is true if we want to collect
every item available, or false
if we don't care about having the complete set.
☑ Add a method addToCollection. In this method, add one to
collected and report the new value. Also if after adding we have
collected all the available items, print a congratulatory message.
☑
Write a toString for this class as follows:
If there are more objects collected than are available, the result
should be something likean overflowing collection with 20 out of 15 items
if there are exactly the same number collected as available
a perfect collection with 15 out of 15 items
if there are fewer collected than are available, it depends whether we
are being completist, so eithera sadly incomplete collection with 10 out of 15 items
ora collection with 10 out of 15 items
☑ [EC] Actually, if the number available is 0, no matter how
many are collected,
the result should benot really a collection at all
adjust your toString accordingly
☑ In your main (after part A), create several Collectors with different values and
check that their toStrings come out correctly
[EC]
☑ 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 and nesting/else-if, print the three ints back out in increasing order. (You
can ignore the case where two numbers are the same)
So whether you were given 2, 1, 3, or 1,2,3 or 3,1,2, you'd print out
1,2,3.
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.