Recitation R3
- Interpret Java, Scanners, and Strings
Spring 2014
CS160: Foundations in Programming
The purpose of this lab is:
- To learn how to interpret simple Java programs
- To learn the Java string methods
- To understand data input using a Java Scanner
- To practice Java data types and casting
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.
2. Simple String functions
Create a R3 project and class in Eclipse, and put the following code into the main method in R3.java:
- Declare a new String variable and set it to your last name,
followed by a comma and space, followed by your first name.
- The names should be capitalized and separated by a space.
- Call the following methods on the string, each in a separate print line:
- length() of the string
- indexOf() the comma character
- charAt() the first letter in the string
- charAt() the last letter in the string
- substring() containing the third up to (not including) the seventh characters
- toUpperCase() of the string
- toLowerCase() of the string
3. Scanner, Types, and Casting
Your TA will help you add to R3.java to do the following:
- Use a Scanner object to read an integer int x;.
- Use a Scanner object to read a floating-point value double d;.
- Type cast x to a byte value and store the result in byte b;.
- Type cast d to an int value and store the result in int y;.
- Display x, b, d, and y, clearly labeled.
- The floating-point value d should be formatted to two decimal places with a DecimalFormat object.
Show your R3.java program to the TA for grading and submit to RamCT to get credit for this lab.
© 2014 CS160 Colorado State University. All Rights Reserved.