Spring Semester 2005

Lecture Notes Three: Variables and types. Keyboard input.

Types of Numbers (Numeric Types)

Last time we looked at two types of numbers:

We will use int to denote the first category of numbers.

(Occasionally long will also be used and explained.)

We will use double as the label for the second category.

(Although float will also be used from time to time).

We use numbers to create expressions, which is a way of calculating other numbers.

The operators we looked at are:

If the two operands in an expression are both integers the result is also an integer.

If one of the two operands in an expression is a double the result will be a double.

So, some examples are:

Precedence of Operators

Some operators have precedence over others:


The order of the operations can be specified by parentheses.

In their absence operations of the same precedence are to be performed left to right.

Here are some examples:

This last one is (hopefully) clear.

Some more examples:

Math.sqrt(...) and Math.pow(...)

Instead of operators we use:

What can we do with these expressions outside of printing their result?

We can store the number they evaluate to, for later use.

For that we use variables, which are:

names for locations that can keep values of a certain type.
The only types we know thus far are:

Declaring Variables

Here's how you declare and initialize a variable of type int:
int n; // declaration 

n = 1; // initialization to 1
n = 1; is an assignment statement:

Here's how you declare and initialize a variable of type int:
double m; // declaration 

m = 1.0; // initialization to 1
You will notice that in the last example
m = 1;
would have worked just as well.

1 is compatible with double and m is now 1.0 as a matter of fact.

In the previous example

n = 6 / 3; 
would have also been correct, but
n = 6.0 / 3.0; 
would give an error. There's no room for the decimal part in n even if it's 0 (zero).

A variable should not be declared more than once.

A variable can changed its value any number of times.

Compatible Types (Casting)

If types are compatible they can also be converted:
m = 6; 

n = (int)2.3 // n contains 2 now
The last assignment uses casting.

In this case we drop the decimal part on purpose.

Reading from the Keyboard (ConsoleReader)

The rest of this lecture will introduce ConsoleReader, which is a kind of Penguin.

   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(
    String readLine() { // instance method 
	String inputLine = "";
	try {
	    inputLine = reader.readLine(); 
	} catch (IOException e) {
	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 
You only need to know how to use it.

A Complete Example

So we will discuss this program:
/* 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

Converting Strings into Numbers

The last thing we need to make clear is that strings of characters are different.

You can't say:

int n = "12"; // won't work
If you really want something like that you'd have to convert:
int n = Integer.parseInt("12"); // now n is set to 12 
If the conversion fails you will find out, the program will crash.

A Review on Strings

Strings are indicated by characters grouped between double quotes.

You need a backslash in front of it (as in \") to indicate a double quote inside a string.

(The backslash is an escape character. It disables the normal meaning of a double quote, as a delimiter.)

The backslash in front of a normal lowercase n indicates a newline.

(You wouldn't otherwise be able to write a newline in the string, since that would break the line.)

To indicate a backslash use the backslash in front of a backslash: \\.

So "\"\\\n" prints as a double quote followed by a backslash and a newline.

Strings could be concatenated using +.

Thus "blue" + "berry" evaluates to "blueberry".

There will be a few more rules to keep in mind.

Last updated by Adrian German for A201/A597/I210 on Tue Jan 18 14:56:06 EST 2005