Spring Semester 2004


Lab Notes Two: Some simple programs, some sample problems.
Goals for this lab: Here now is the interactive conversion program announced at the end of Lecture Notes Four.

First a sample session of working with the program (on Unix). I marked the user's answers with blue, but this just for illustration purposes in these lab notes. Don't expect the program to actually print in color when you compile and run it, of course.

frilled.cs.indiana.edu%javac Conversion.java
frilled.cs.indiana.edu%java Conversion
Hi my name is Hal. What is your name?
Dave
Hello, Dave! How many dollars do you want to convert?
(Please type an integer value, no decimal part)
40
I see, you want to convert 40 dollars in British pounds. Very well...
What is the conversion rate today?
0.65
Well, Dave for 40 dollars you can get: 26.0 pounds.
Thank you for using Hal! Good-bye.
frilled.cs.indiana.edu%
Here's the actual Conversion class. I placed all the comments in light grey to make the reading of the code a bit easier. (To better read the comment just highlight it with your mouse.)
/* A conversion program that illustrates how one can read input
   from the keyboard using the textbook's ConsoleReader class */ 

class Conversion {
    public static void main(String[] args) {
	ConsoleReader console = new ConsoleReader(System.in); 
	// now we can read from 'console' 
	System.out.println("Hi my name is Hal. What is your name?"); 
	// greet the user
	String name = console.readLine(); 
	// wait for input and collect it (a String, for the name) 
	System.out.print("Hello, " + name + "! "); 
	// echo the name to the user, raising user's confidence in us 
	System.out.println("How many dollars do you want to convert?"); 
	// approach the user directly, offer your services 
	System.out.println("(Please type an integer value, no decimal part)"); 
	// instruct the user what limitations you have (accepting only int's)
	int amount = console.readInt(); 
	// wait for the user to provide the sum to be converted 
	System.out.println("I see, you want to convert " + amount + 
			   " dollars in British pounds. Very well..."); 
	// talk to the user, be friendly, echo information frequently 
	System.out.println("What is the conversion rate today?"); 
	// ask the user for the last piece of input 
	double rate = console.readDouble(); 
	// wait for the conversion rate, which can have a fractional part
        System.out.println("Well, "+ name + " for " + amount + " dollars " + 
			   "you can get: " + rate * amount + " pounds.");
	// do the calculation and report it to the user 
	System.out.println("Thank you for using Hal! Good-bye."); 
	// thank the user for interest and say good-bye
    } 
}
And here's the ConsoleReader class. This class is given to you for the purpose of doing keyboard input. You don't need to understand the code right now, it will become clearer at the end of chapter 3. However we think it's good for you to be exposed to what it looks like, and to slowly become familiar with it, and Java code and I/O (which will be covered at some point in class later).
/*******************************************************
   ConsoleReader class is used for keyboard input. 
   Just keep the source code of this class (the file)
   in the same directory in which your other program
   (the one that needs user input) resides. 

   In this particular case keep it in the same folder
   with Conversion.java that has been presented above. 
********************************************************/ 

import java.io.*; // I/O package needed 

class ConsoleReader { 
    ConsoleReader(InputStream inStream) { // constructor 
	reader = new BufferedReader(
                   new InputStreamReader(
                     inStream));     
    }
    String readLine() { // instance method 
	String inputLine = "";
	try {
	    inputLine = reader.readLine(); 
	} catch (IOException e) {
	    System.out.println(e); 
	    System.exit(1); 
	} 
	return inputLine; 
    }
    int readInt() { // instance method 
	String inputString = readLine(); 
	int n = Integer.parseInt(inputString); 
	return n; 
    }
    double readDouble() { // instance method 
	String inputString = readLine(); 
	double x = Double.parseDouble(inputString); 
	return x; 
    } 
    private BufferedReader reader; // instance method 
}
In your programs, from now on, keep using this class for user input from the keyboard, as it will provide a simple, uniform way of doing keyboard input. Here now is also a diagrammatic description of the fundamental difference between primitive and reference types, that we looked at in the notes:

Reference types (using Rectangle)

Rectangle a = new rectangle(10, 20, 30, 40); 
Rectangle b = a; 
The picture looks as follows:

Now if you have

a.translate(3, 3); 
System.out.println(b);
you will be able to see the change. Both a and b point to one and the same thing, an essentially anonymous object, to which we refer as both a and b. So changes made using the a name can be seen by looking at the object using the other name, that is, b.

Primitive types (using int)

int a = 3;
int b = a; 
The picture looks as follows:

The big difference is that the primitive value is copied into the storage location. So each location has its own copy. It just works that way with the numbers (as primitive types) but doesn't with objects (reference types). That's how it works. With reference types, what the variable holds is a reference, the arrow. With primitive types, the variable holds a value, a copy of the actual value.

Now if you have

a = 10; 
System.out.println(b);
you will see that the value of b has not been updated.

Each location has its own (copy of the) value, and changing one does not affect the other. This is an important difference, we refer to it as the by value vs. by reference contrast, and it will be useful for you to remember it from now on when you reason about and design programs.

Your Lab Assignment Two could be similar to

And now the practice problems:

Try to solve these problems to practice some of the things you learned this week. In the examples that follow, your program's answers are always in blue, to distinguish them from what you would type as a user. Remember: the resulting programs are elementary, and the problems are interesting.

1. Write a program that prompts the user for two integers and then prints

  • The sum
  • The difference
  • The product
  • The average
  • The distance (absolute value of the difference)
  • The maximum (the larger of the two )
  • The minimum (the smaller of the two)
Here's a sample run with your program:

frilled.cs.indiana.edu%java One
Please enter your first integer number, then press Enter.
3
Please enter your second integer number, then press Enter.
6
3 + 6 = 9
3 - 6 = -3
3 * 6 = 18
avg(3, 6) = 4.5
dist(3, 6) = 3
max(3, 6) = 6
min(3, 6) = 3
frilled.cs.indiana.edu%


2. (Giving change) Implement a program that directs a cashier how to give change.

The program has two inputs:

  • the amount due and
  • the amount received from the customer.
Compute the difference, and compute the
  • dollars,
  • quarters,
  • dimes,
  • nickels, and
  • pennies
that the customer should receive in return.

Hint: First transform the difference into an integer balance, denominated in pennies. Then compute the whole dollar amount. Subtract it from the balance. Compute the number of quarters needed. Repeat for dimes and nickels. Display the remaining pennies.

Here's a sample run with your program:
frilled.cs.indiana.edu%java Two
Type the amount due then press enter.
3.72
Type the amount received then press enter.
5
Give 1.28 in change as follows: 
   5 quarters
   0 dimes
   0 nickels
   3 cents
frilled.cs.indiana.edu%java Two
Type the amount due then press enter.
0.08
Type the amount received then press enter.

0.5
Give 0.42 in change as follows: 
   1 quarters
   1 dimes
   1 nickels
   2 cents
frilled.cs.indiana.edu%

3. Write a program that asks the user to input
  • The number of gallons
  • The fuel efficiency
  • The price
Then print how far the car can go with the gas in the tank and print the cost per 100 miles.
Here's a sample run with your program:
frilled.cs.indiana.edu%java Three 

Please enter the number of gallons then press enter.
32
Please enter the fuel efficiency (miles/gallon) then press enter. 
16
Please enter the price per gallon, then press enter.
1.54
With the gas in the tank you can go 512.0 miles, 
at a cost of 9.625 per 100 miles.
frilled.cs.indiana.edu%java Three 
Please enter the number of gallons then press enter.
2.8
Please enter the fuel efficiency (miles/gallon) then press enter. 

18.5
Please enter the price per gallon, then press enter.
1.48
With the gas in the tank you can go 51.8 miles, 
at a cost of 8.0 per 100 miles.
frilled.cs.indiana.edu%

4. Write a program that reads two times in military format (0900, 1730) and prints the number of hours and minutes between the two times. Here is a sample run. User input is in color.
Please enter the first time: 0900
Please enter the second time: 1730
8 hours 30 minutes
Extra credit if you can deal with the case that the first time is later than the second time:
Please enter the first time: 1730
Please enter the second time: 0900

15 hours 30 minutes
Here's a sample run with your program:
frilled.cs.indiana.edu%java Four
Please enter the first time: 0920
Please enter the second time: 1025

1 hours 5 minutes
frilled.cs.indiana.edu%java Four
Please enter the first time: 1025
Please enter the second time: 0920
22 hours 55 minutes
frilled.cs.indiana.edu%

5. Run the following program, and explain the output you get. The program is a bit incorrect, but can you guess what it was meant to do (its intended purpose)? Run it, experiment a bit with it to see if you can figure it out.
public class Five 
{ public static void main(String[] args) 
  { ConsoleReader console = new ConsoleReader(System.in); 
    int total = 0; 
    System.out.println("Please enter a positive number:"); 
    int x1 = Integer.parseInt(console.readLine());
    System.out.println("total = " + total); 
    total = total + 1 / x1; 
    System.out.println("total = " + total); 
    System.out.println("Please enter a positive number:"); 
    int x2 = Integer.parseInt(console.readLine());
    total = total + 1 / x2; 
    System.out.println("total = " + total); 
    total = total * x1 * x2 / 2; 
    System.out.println("total = " + total); 
    System.out.println("The average is " + total); 
  }
}
Note the trace messages, which are inserted to show the current contents of the total variable. After you determine what the program is supposed to do, fix up the program, run it with the trace messages in place to verify that it works correctly, and remove the trace messages.

6. Write a program that transforms numbers
1, 2, 3, ..., 12
into the corresponding month names
January, February, March, ..., December
Hint: Make a very long string
"January February March......."
in which you add spaces such that each month name has the same length.

Then use substring to extract the month you want.

Here's a sample run with your program:
frilled.cs.indiana.edu%java Six
Please enter a month number from 1 to 12.
2
February  
frilled.cs.indiana.edu%java Six
Please enter a month number from 1 to 12.
12
December  
frilled.cs.indiana.edu%java Six
Please enter a month number from 1 to 12.

1
January   
frilled.cs.indiana.edu%java Six
Please enter a month number from 1 to 12.
14
Exception in thread "main" [...]
frilled.cs.indiana.edu%


Last updated: Jan 20, 2004 by Adrian German for A201