CS160: Foundations in Programming: Spring 2015
Recitation R2 - Java Expressions, Strings, and Scanners
The goals of this lab are as follows:
- Learn about Java variables and expressions
- Understand integer versus floating point math
- See how the order of precedence affects expressions
- Learn about calling methods on a String object
- Learn how to use a Scanner object to read input
- Find out the difference between println, print, and printf.
- Learn how to format output using printf.
Create a new Java Project named R2, and make a class named R2.
Your TA will help you to print out the values of the following mathematical expressions:
Think about the above behavior and be prepared to answer the following questions:
- 15 + 4
- 15 / 4
- 15.0 / 4.0
- 15.0 / 4
- 15 % 4
- 4 - 8 * 3
- (4 - 8) * 3
- 0.1 + 0.2 - 0.3
- Explain the difference (or lack of it) in the result of 15 / 4, 15.0 / 4.0 and 15.0 / 4.
- Explain the difference (or lack of it) in the result of 4 - 8 * 3 and (4 - 8) * 3.
- Explain the result of 0.1 + 0.2 - 0.3
Overview of Simple String Methods
You TA will discuss the follow String methods:
- length() of the string
- indexOf() the comma character
- charAt() the first letter in the string
- substring() containing the third up to (not including) the seventh characters
- toUpperCase() of the string
- toLowerCase() of the string
IMPORTANT: This code is what will be graded. Comment out all previous work before
submitting (using: // or /* */). You are free to borrow code that you've already written.
If you have any doubts or questions, ask the TA:
- A) Create a Scanner object.
- B) Create an integer variable called i and initialize it to 0.
- C) Create a double variable called d and initialize it to 0.0.
- D) Do the following two things:
- Print the prompt "Enter an integer: " using System.out.print().
- Use the Scanner object you created to read in an integer to i.
- E) Print "You entered: " followed by the value of the integer variable i.
- F) Do the following two things:
- Print the prompt "Now enter a double: " using System.out.print().
- Use the Scanner object you created to read in a double to d.
- G) Print "Now you entered: " followed by the value of d, formatted to two decimal places.
- H) Create a String variable myString and initialize to "Babushka".
- I) Print the result of calling length() on myString.
- J) Print the result of calling charAt() on myString to print third character in myString.
- K) Print the result of calling indexOf() on myString to print the index of 'k' in myString.
- L) Print the result of calling toUpperCase() on myString.
- Make sure your R2.java compiles and produces the correct output.
- Check your R2.java using preliminary testing on the Checkin tab.
You must submit your R2.java program using the Checkin tab on the course website.
© 2015 CS160 Colorado State University. All Rights Reserved.