Colorado State University

Recitation R3 - Interpret Java, Scanners, and Strings
Spring 2014

CS160: Foundations in Programming


The purpose of this lab is:
  1. To learn how to interpret simple Java programs
  2. To learn the Java string methods
  3. To understand data input using a Java Scanner
  4. 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:

3. Scanner, Types, and Casting

Your TA will help you add to R3.java to do the following:
  1. Use a Scanner object to read an integer int x;.
  2. Use a Scanner object to read a floating-point value double d;.
  3. Type cast x to a byte value and store the result in byte b;.
  4. Type cast d to an int value and store the result in int y;.
  5. Display x, b, d, and y, clearly labeled.
  6. 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.