Welcome to Lab 2

By the end of this Lab you should be able to do the following.

Lab Topics

Input Basic Data Types

We have already used the System.out object and used it to do basic output to the screen. The Java API has another object, System.in, which refers to the standard input device. The standard input device is normally the keyboard. You can use the System.in object to read keystrokes that have been typed at the keyboard. However, using System.in is not as simple and straightforward as using System.out because the System. in object reads input only as byte values. This isn’t very useful because programs normally require values of other data types as input. To work around this, you can use the System.in object in conjunction with an object of the Scanner class. The Scanner class is designed to read input from a source (such as System.in) and it provides methods that you can use to retrieve the input formatted as primitive values like ints and doubles or strings.

First, you create a Scanner object and connect it to the System.in object. Here is an example of a statement that does just that:

Scanner keyboard = new Scanner(System.in);

In the first part of the statement,

Scanner keyboard

declares a variable named keyboard. The data type of the variable is Scanner. The second part of the statement is as follows:

= new Scanner(System.in);

The first thing we see in this part of the statement is the assignment operator (=). The assignment operator will assign something to the keyboard variable. After the assignment operator we see the word new, which is a Java key word. The purpose of the new key word is to create an object in memory. The type of object that will be created is listed next. In this case, we see Scanner ( System. in) listed after the new key word. This specifies that a Scanner object should be created, and it should be connected to the System. in object. After the statement executes, the keyboard variable will reference the Scanner object that was created in memory.

There is nothing special about the name keyboard. We simply chose that name because we will use the variable to read input from the keyboard. The Scanner class has methods for reading strings, bytes, integers, long integers, short integers, floats and doubles. For example, the following code uses an object of the Scanner class to read an int value from the keyboard and assign the value to the number variable.

int number;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter an integer value: ");
number = keyboard.nextlnt();

The last statement shown here calls the Scanner class’s nextlnt method. The nextlnt method formats an input value as an int, and then returns that value. Therefore, this statement formats the input that was entered at the keyboard as an int, and then returns it. The value is assigned to the number variable. The following is a partial list of the Scanner classes most popular methods. See the library listing for complete information

nextByte

Example Usage:

byte x;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a byte value: ");
x = keyboard.nextByte();

Description: Returns input as a byte.

nextDouble

Example Usage:

double number;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a double value: ");
number = keyboard.nextDouble();

Description: Returns input as a double.

nextEloat

Example Usage:

float number;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a float value: ");
number = keyboard.nextFloat();

Description: Returns input as a float.

nextlnt

Example Usage:

int number;
Scanner keyboard = new Scanner(System.in);
system.out.print("Enter an integer value: ");
number = keyboard.nextInt()

Description: Returns input as an int.

nextLine

Example Usage:

String name;
Scanner keyboard = new Scanner(System.in)
System.out.print("Enter your name: ");
name = keyboard.nextLine()

Description: Returns input as a String.

nextLong

Example Usage:

long number;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a long value: ");
number = keyboard.nextLong()

Description: Returns input as a long.

nextShort

Example Usage:

short number; 
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a short value: ");
number = keyboard.nextShort();

Description: Returns input as a short.

Reading a single character from the Keyboard

Sometimes you will want to read a single character from the keyboard. For example, your program might ask the user a yes/no question, and specify that he or she type Y for yes or N for no. Unfortunately the Scanner class does not have a method for reading a single character. A simple method for reading a character is to use the Scanner class’s nextLine method to read a string from the keyboard, and then use the String class’s charAt method to extract the first character of the string. This will be the character that the user entered at the keyboard. Here is an example:

String input; // To hold a line of input
char answer; // To hold a single character

// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);

// Ask the user a question.
System.out.print("Are you having fun? (Y=yes, N=no) ");
input = keyboard.nextLine(); // Get a line of input.
answer = input.charAt(0); // Get the first character.

The input variable references a String object. The last statement in this code calls the String class’s charAt method to retrieve the character at position 0, which is the first character in the string. After this statement executes, the answer variable will hold the character that the user typed at the keyboard.

The following code has some examples of how to do simple input into Java

/**
 * Shows the Scanner class being used to read a double, a String, and an int.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */

import java.util.Scanner;

public class Input{
    String name;        // To hold a name
    int hours;          // Hours worked
    double payRate;     // Hourly pay rate
    double grossPay;    // Gross pay
    
    public static void main(String[] args){
        Input input = new Input();
        input.run();
    }
    
    public Input(){
        name = "";
        hours = 0;
        payRate = 0.0;
        grossPay = 0.0;
    }
    
    public void run(){
        // Create a Scanner object to read input.
        Scanner keyboard = new Scanner(System.in);

        // Get the user's name.
        System.out.print("What is your name? ");
        name = keyboard.nextLine();
   
        // Get the number of hours worked this week.
        System.out.print("How many hours did you work this week? ");
        hours = keyboard.nextInt();

        // Get the user's hourly pay rate. 
        System.out.print("What is your hourly pay rate? "); 
        payRate = keyboard.nextDouble();

        // Calculate the gross pay. 
        grossPay = hours * payRate;
        
        // Display the resulting wages
        System.out.print("Hello "+name); 
        System.out.print(" Your gross pay is $"+grossPay); 
    }
}
 

Programming Problem

Get the users birth date. Get the current date from the user. Calculate and output the number of complete years that the user has been alive along with the complete number of Months, Days, Hours, Minutes, Seconds, MicroSeconds, and Gigaseconds that that person has been alive. The output of your program should look a lot like this...

Enter day of birth 22
Enter month of birth 5
Enter year of birth 1973
Enter current day 26
Enter current month 1
Enter current year 2012
You were born 22/5/1973
It is now 26/1/2012
You have been alive 38 complete years
You have been alive 463 complete months
You have been alive 14119 days
You have been alive 338856 hours
You have been alive 20331360 minutes
You have been alive 1219881600 seconds
You have been alive 1219881600000000 microseconds
You have been alive 1.2198816 gigaseconds