Recitation R3
- Scanners & Strings
Fall 2013
CS160: Foundations in Programming
1. Interpret Java
What does the following code print out?
DO NOT RUN THIS CODE. Try and figure out what it does just by looking at it.
You are not graded on correctness, this is purely to help you understand java.
|
//Interpreting Java
public class Interpret1
{
public static void main( String[ ] args )
{
// Variables
int i = 15;
int j = 6;
double x = 7.0;
double y = 4.0;
// Expressions
System.out.println("1) i / j = " + (i / j));
System.out.println("2) i % j = " + (i % j));
System.out.println("3) x / y = " + (x / y));
System.out.println("4) i / y = " + (i / y));
System.out.println("5) x - 6 * y = " + (x - 6 * y));
System.out.println("6) (x - 6) * y = " + ((x - 6) * y));
// Caution, this is a trick question!
System.out.println("7) i + j = " + i + j);
// Letters
char a, b, c;
a = 'b';
System.out.println("8) " + a);
b = 'c';
System.out.println("9) " + b);
c = (char) (b + 2);
System.out.println("10) " + c);
}
}
Write your answer down (you should have 10 lines of output)
and your TA will go over it once everyone has finished.
The purpose of this lab is:
- To understand data input using a Java Scanner
- To practice Java data types and casting
- To learn the Java string methods
2. Scanner, Types, and Casting
Your TA will help you create a new project called R3. Within this project the
TA will help you write a program called R3.java that shows
how scanner works, and
demonstrates how casting works by performing the following tasks:
- Use Scanner to read in an integer x and display it.
- Use Scanner to read a floating-point value d.
- Type cast d to an int value and store the result in y.
- Display d and y clearly labeled. d should be
formatted to two decimal places.
- Type cast d to a byte value and store the result in b.
3. Simple String functions
Your TA will help you add to your R3.java program to:
- Add a new String variable and set it to be equal to your full name.
- Call the following methods on that string, each in a separate print line:
- length()
- indexOf() the first letter of your last name
- charAt() the first letter and the last
- substring() the third through the seventh characters
- toUpperCase() the string
- toLowerCase() the string
Show your R3.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.