Recitation R4
- Conditionals
Fall 2013
CS160: Foundations in Programming
The purpose of this lab is to learn about the conditionals in Java:
and when to use them.
If Statements
- Create a new class in Eclipse called R4.
- Check the box to have Eclipse add the main method for you.
- The following should be coded in the main method.
- Instantiate a scanner.
- Use the scanner to read an integer from the user (the console) and store it into a variable.
- Write an if statement with a conditional evaluating to true when the number from the user is negative.
- The statement should turn the negative number positive and store it back in the variable.
- Print the number to the console.
If, Else-If Block Statements
- Have your scanner take in a double and store it into a variable named
salary
.
- Create a new double named
taxes
. Leave it uninitialized
- Write an if/else block that satisfies the following tax brackets
- when 0 ≤
salary
< 1,000 then:
you pay no taxes.
- when 1,000 ≤
salary
< 10,000 then:
you pay 0.15 times your salary in taxes.
- when 10,000 ≤
salary
< 50,000 OR 100,000 ≤ salary
< 1,000,000 then:
you pay 0.2 times your salary in taxes.
- when 50,000 ≤
salary
< 100,000 then:
you pay 0.18 times your salary in taxes.
- otherwise:
you pay a flat $200,000 tax.
- Print
taxes
to the console
- Is it possible that
taxes
will not have a value by the time it gets printed?
Write a comment explaining why, or why not.
Switch Statements
- Have your scanner take in a String and store it into a variable.
- Write a switch statement, that switches on the first character of the string, with at least these cases:
- 'a' or 'A' should print:
'A' is for Abstract Algebra, the kind of algebra Pablo Picasso would enjoy!
- 'b' or 'B' should print:
'B' is for Boolean Logic, the best of all logics!
- 'c' or 'C' should print:
'C' is for the C language, an old and incredibly unforgiving programming language developed in 1969 at AT&T Bell Labs
- 'j' or 'J' should print:
'J' is for Java, the nicest language you'll ever meet, developed by Sun Microsystems in 1991
- otherwise it should print:
Oh, we don't have anything for that letter... Maybe you could add something in?
- Don't forget your break statements!
- Add a comment explaining why someone might use a switch rather than an if-else.
Show your R4.java program to the TA for grading and submit to RamCT to get credit for this lab.
© 2013 CS160 Colorado State University. All Rights Reserved.