INTRODUCTION TO PACKAGES  AND  INPUT / OUTPUT IN JAVA

TOPICS 



Packages, Classes, Methods and the import Statement
Input in Java using the Scanner class
More about Output in Java (printf)
Sample Programs:

Program #1: BMI Program Example (interactive input)
Program #2: Testing interactive input using the
Scanner class (1)
Program #3: Testing interactive input using the
Scanner class (2)
Program #4: Testing interactive input using the
Scanner class (nextLine)
Program #5: Testing output with
printf

OUTLINE



Packages, Classes, Methods and the import Statement

Java has many predefined packages, classes, and methods.

Definitions:

To make use of the existing Java classes, methods, and identifiers, you must specify the packages that contain the appropriate information using the reserved word import and importing the contents of the package into the program as follows:

import packageName.*;

Note # 1: If you use the character * in the import statement, as in the statement: import java.util.*; then the compiler determines the relevant class(es) used in the program. You can also be specific and give the name of the class needed (Example: import java.util.*; vs import java.util.Scanner;)
Note # 2: The primitive data types are directly part of the Java language --> no need to import any package in current program.
Note # 3: (Very important!) The class
String is contained in the package java.lang --> no need to import classes from the package java.lang, because the system automatically does it for you.

With these notes in mind, the skeleton of a Java program looks like this:

import statements (if any)

public class ClassName
{
    declare named class constants: public static final ....

    public static void main(String[] args)
    {
        variable declarations
        executable statements
        ...
        ...
    } //close main()
} //close class

As stated at the beginning of these notes, Java has many predefined packages, classes, and methods. How to use them in a Java program?
To use a predefined method you must know:

Example of a method call:

import java.lang.*; //import the package; NOT NEEDED, DONE BY THE SYSTEM
result = Math.pow(2, 3); //calls the power method from class Math

Input

We use two different methods to initialize a variable with some data:

1. Assignment statements (discussed).
2. Input statements to get data (from the standard input device or from a file).

Input Statements

To put data into variables from the standard input device, we first create an input stream object and associate it with the standard input device (usually the keyboard) using the following statement:

Scanner input = new Scanner(System.in);

This statement creates the input stream object input and associates it with the standard input device. The object input can read  the next input using one of these calls:  input.nextInt(), input.nextDouble(),input.next(), input.nextLine(). Check the table below for a list of available methods.

Note #1: System.in is called a standard input stream object and is designed to input data from the standard input device. By using System.in, we first create a Scanner object, such as input, so that the data can be extracted in a desired form.

Example of variable initialization:

Consider the following declaration:

int how_many;

You can initialize the variable how_many to a value of 25 either by using the assignment statement:

how_many = 25;

or by executing the following statement and entering 25 during program execution:

Scanner input = new Scanner(System.in);
how_many = input.nextInt();

If you use the assignment statement (how_many = 25;) to initialize how_many, then you are stuck with the same value each time the program runs unless you edit the source code, change the value, recompile, and run. By using an input statement (how_many = input.nextInt();), the user is prompted to enter a value, and the value entered is stored in how_many. Therefore, an input statement is much stronger than an assignment statement and allows for flexibility in a program.

The Scanner class: The Scanner class allows the user to read values of various types and it is found in the java.util package (start  your program with: import java.util.Scanner;)  The class Scanner has many methods - for now we are going to discuss just some of them, in order to allow interactive input.We will only discuss a small useful subset --> the methods that allow reading in numeric values from the standard input device (in most cases, the keyboard)  and later from files, without having to convert them from strings and determine if there are more values to be read.

Numeric and String methods:
 

Method

Return

int nextInt()

Returns the next token as an int. If the next token is not an integer, InputMismatchException is thrown.

long nextLong()

Returns the next token as a long. If the next token is not an integer, InputMismatchException is thrown.

float nextFloat()

Returns the next token as a float. If the next token is not a float or is out of range, InputMismatchException is thrown.

double nextDouble() 

Returns the next token as a double. If the next token is not a doubleor is out of range, InputMismatchException is thrown.

String next()

Finds and returns the next complete token from this scanner and returns it as a string; a token is usually ended by whitespace such as a blank or line break. If no token exists, NoSuchElementException is thrown.

String nextLine()

Returns the rest of the current line, excluding any line separator at the end.

void close()

Closes the scanner.

The Scanner looks for tokens in the input. A token is a series of characters that ends with what Java calls whitespace. A whitespace character can be a blank, a tab character, a carriage return, or the end of the file. Thus, if we read a line that has a series of numbers separated by blanks, the scanner will take each number as a separate token. Although we have only shown four numeric methods, each numeric data type has a corresponding method that reads values of that type.
The numeric values may all be on one line with blanks between each value or may be on separate lines. Whitespace characters (blanks or carriage returns) act as separators. The next method returns the next input value as a string, regardless of what is keyed.

Reading a Single Character: Assume the next input is a single printable character, say 'Z', and some_char is a char variable. In order to input Z into some_char, we can use the following statement:

Scanner input = new Scanner(System.in);
char some_char;
some_char = input.next().charAt(0);

Example: Given the following input:

25 55
123456789
12345.33 Bye

and the following code segment:

Scanner input = new Scanner(System.in);

int n1 = input.nextInt(); // n1 = 25
float f1 = input.nextFloat(); // f1 = 55.0 --> reads an integer, stored as a float (no ambiguity)
long n2 = input.nextLong(); // n2 = 123456789
double f2 = input.nextDouble(); // f2 = 12345.33
String message = input.next(); // message = Bye

Note #2: The  method nextFloat reads an integer and stores it as a float value.  This is legal because an integer value can be stored exactly as a real value; there is no ambiguity.  If we had keyed a decimal point after the 55 and attempted to store a float as an integer, the system would have thrown an InputMismatchException (a checked exception) regardless of whether or not a non-zero value followed the decimal point. An arbitrary real number cannot be stored exactly as an integer; it is ambiguous.  Remember that in Java anything ambiguous is illegal.

Note #3: The method nextLine reads the rest of the line and returns it as a string.  The carriage return is consumed but is not appended to the string.  All the numeric reads do not consume the whitespace, so if a nextLine is issued after a numeric read and the numeric value is at the end of the line, nextLine returns the empty string.  The method nextLine never jumps over a carriage return to get the next line of input. Take a look at the next program and at Program #4 to see how this method is working.

Here is an example of a program that uses methods from the Scanner class, followed by 3 samples for output, to help you understand how the output was generated.

//**********************************************************************
// Reading numeric values using the Scanner class
//**********************************************************************
//import packages
import java.util.Scanner;

public class TestInput1 {
    public static void main(String[] args) {
        // Declarations
        Scanner input = new Scanner(System.in);
        int n;
        long long_n;
        float float_n;
        double double_n;
        String str1;
        String str2;
        // Prompt for input
        System.out.println("Enter an integer, a long integer, a floating-point ");
        System.out.println("number, another floating-point number, and a string.");
        System.out.println("Use a blank space or return to separate them.");
        // Get input
        n = input.nextInt();
        long_n = input.nextLong();
        float_n = input.nextFloat();
        double_n = input.nextDouble();
        str1 = input.nextLine();
        //Prompt for more input
        System.out.print("Now enter another string: ");
        str2 = input.next(); //This line is changed in Sample Output #3
        //Output
        System.out.println("You entered: ");
        System.out.println(n + " " + long_n + " " + float_n + " " + double_n + " " + str1 + " and " + str2);
    }
}

Sample output #1:

Enter an integer, a long integer, a floating-point
number, another floating-point number, and a string.
Use a blank space or return to separate them.
25 55 123456789 12345.33 Hi!
Now enter another string: Bye!
You entered:
25 55 1.23456792E8 12345.33  Hi! and Bye!

Sample output #2:

Enter an integer, a long integer, a floating-point
number, another floating-point number, and a string.
Use a blank space or return to separate them.
25 55 123456789 12345.33 Hi!
Now enter another string: Bye, bye!
You entered:
25 55 1.23456792E8 12345.33  Hi! and Bye,

Sample output #3: Change the code to str2 = input.nextLine();

Enter an integer, a long integer, a floating-point
number, another floating-point number, and a string.
Use a blank space or return to separate them.
25 55 123456789 12345.33 Hi!
Now enter another string: Bye, bye!
You entered:
25 55 1.23456792E8 12345.33  Hi! and Bye, bye!

Boolean Methods: The class Scanner also has some Boolean methods to determine if there are more values to be read and check if the next value in input has the expected type. --> To be discussed later.
Input from files: To read from a file rather than the keyboard, we have to instantiate a Scanner object with a FileReader object  rather than System.in. --> To be discussed later.

More about Output in Java (using printf)

So far we have used System.out.print (sends output to the current line, without moving to the beginning of a new line) and System.out.println (sends output to the current line, and then it moves to the beginning of a new line --> a new line added at the end of the output). The problem with both is that particularly with floating-point numbers we have no control over how many spaces are occupied, because both methods cannot directly format in a specific manner --> need to format the output and control the number of decimal places. This can be achieved in Java by using the printf method, originated in the C language. The method provides a wide range of formatting options  to better control the output to the console.

Syntax (simplified):

System.out.printf(String format, item);

where: format is a string that may consist of substrings and format specifiers (specify how an item should be displayed in output). The item  is a numeric value, character, boolean value, or a string. Each format specifier starts with the percent (%) sign. The table below describes some common specifiers for different data types:
 

Specifier

Output

Example

%b

a boolean value 

true / false

%c

a character

'A', '?', '('

%d

a (decimal) integer

500

%f

a flaoting-point number

1234.358000 (by default, generates floating-point numbers with 6 trailing numbers after the decimal point)

%e

a number in standard scientific notation

1.234358e+03

%s

a string

"Testing printf"

Example:

double pi = Math.PI;
System.out.printf("pi = %7.3f\n", pi);

results in the console output: pi =   3.142
Some explanations:

Syntax (more general):

System.out.printf("%[flags][width][.precision]conversion symbol, item);

Note #4: Expressions in square brackets are optional.
Note #5: A flag indicates an option for the format. For example,
'+' requires that a sign be include and '0' requires padding with zeros.
Note #6: If the number in the option
width  is too small to output the value, the output is expanded to the required width.
Note #7: If the
precision specified is greater that the precision of the value in output, extra zeros are added at the end.
Note #8: The output is right-justified by default. To force the output to be left-justified --> may use negative values for
width.
Take a look at Program #5 for a sample program using
printf with different format specifiers.

Sample Programs

Program #1: The BMI Program (Lecture #3) with interactive input

//import packages
import java.util.Scanner;

public class BMICalculator {
    public static void main(String[] args) {
        // declare variables
        Scanner input = new Scanner(System.in);
        double height;
        double weight;
        double bmi;
        //Prompt for input
        System.out.print("Enter an height and weight, separated by a space: " );
        // Get input
        height = input.nextDouble();
        weight = input.nextDouble();
        // compute BMI
        bmi = weight / (height * height) * 703;
        // print results
        System.out.println("Current BMI: " + bmi);
        //Prompt for more input
         System.out.print("Enter target weight: " );
        // Get input
        weight = input.nextDouble();
        // recompute BMI; same height, change weight
        bmi = weight / (height * height) * 703;
        // print new results
        System.out.println("Target BMI: " + bmi);
    }
}

Sample Output:
Enter an height and weight, separated by a space: 5.9 230
Current BMI: 4644.929617925884
Enter target weight: 190
Target BMI: 3837.115771330077

Program #2: Test  for input using the Scanner class

//import packages
import java.util.Scanner;

public class TestInput2 {
    public static void main( String args[] ) {
        // Declarations
        Scanner input = new Scanner(System.in);
        String sentence;
        int number, result;
        double real;
        // Prompt for input
        System.out.print("Enter a sentence: ");
        // Get input
        sentence = input.nextLine();
        //Output
        System.out.print("The sentence entered was:  " + sentence + "\n");
        // Prompt for input
        System.out.println("Enter an integer number: " );
        // Get input
        number = input.nextInt();
        //Output
        System.out.println("The integer number entered was: " + number );
        // Prompt for input
        System.out.println("Enter a floating-point number: ");
        // Get input
        real = input.nextDouble();
        //Output
        System.out.println("The floating-point number entered was: " + real );
        //calls power method in class Math ; assign the return to a double
        real = Math.pow(number, 3);
        System.out.println("The value of " + number + " raised to the exponent 3 is " + real);
        //could use the method call in output
        System.out.println("The value of " + number + " raised to the exponent 4 is " + Math.pow(number, 4));
    }
}
Sample Output:
Enter a sentence: Testing the Scanner class
The sentence entered was:  Testing the Scanner class
Enter an integer number: 3
The integer number entered was: 3
Enter a floating-point number: 3.1234567
The floating-point number entered was: 3.1234567
The value of 3 raised to the exponent 3 is 27.0
The value of 3 raised to the exponent 4 is 81.0

Program #3: Test  for input using the Scanner class

//import packages
import java.util.Scanner;

public class TestInput3 {
    public static void main( String args[] ) {
        // Declarations
        Scanner input = new Scanner(System.in);
        String firstName;
        String lastName;
        int age;
        double gpa;
        String major;
      // Prompt for input
        System.out.print("Enter first name, last name, age, GPA, and major, separated by spaces: ");
        // Get input
        firstName = input.next();
        lastName = input.next();
        age = input.nextInt();
        gpa = input.nextDouble();
        major = input.next();
        //Output (echo)
        System.out.println("Name " + lastName + ", " + firstName);
        System.out.println("Major: " + major );
        System.out.println("Age: " + age);
        System.out.println("GPA: " + gpa );
    }
}

Sample Output:
Enter first name, last name, age, GPA, and major, separated by spaces: JOHN SMITH 20 3.53 COSC
Name SMITH, JOHN
Major: COSC
Age: 20
GPA: 3.53

Program #4: Test for  nextLine (Scanner class)

import java.util.Scanner;

class TestInput4 {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        int n1 = input.nextInt();
        String str1 = input.nextLine();
        float f1 = input.nextFloat();
        String str2 = input.nextLine();
      //Output
        System.out.println("n1 = " + n1);
        System.out.println("str1 = " + str1);
        System.out.println("f1 = " + f1);
        System.out.println("str2 = " + str2);
    }
}
 

Sample Input

Sample Output

25 55
123456789
12345.33

n1 = 25
str1 =  55
f1 = 1.23456792E8
str2 = 

25 55
123456789 12345.33

n1 = 25
str1 =  55
f1 = 1.23456792E8
str2 =  12345.33

25
55

n1 = 25
str1 = 
f1 = 55.0
str2 = 

Program #5: Test  for output using the printf method.

public class Test_printf {
    public static void main(String args[]) {
        System.out.print("\nDisplay numeric values using different format specifiers with printf.");
        System.out.print("\n=====================================================================");
        System.out.printf("\nSome formats for integers:");
        System.out.printf("\n-------------------------- \n");
        System.out.printf("Using d (decimal format) for 5 will display: " + "%d\n" , 5);
        System.out.printf("Using +d (decimal signed format) for 5 will display: " + "%+d\n" , 5);
        System.out.printf("Using (d (negative decimal option) for -5 will display: " + "%(d\n" , -5);
        System.out.printf("Using  4d (decimal, specified width) for 5 will display: " + "%4d\n" , 5);
        System.out.printf("Using 04d (decimal, specified width, padding with 0s) for 5 will display: " + "%04d\n" , 5);

        System.out.printf("\nSome formats for floating-point numbers:");
        System.out.printf("\n----------------------------------------\n");
        System.out.printf("Using f (default floating-point format) for 12345.12345 will display: " + "%f\n", 12345.12345);
        System.out.printf("Using ,f (floating-point with commas format) for 12345.12345 will display: " + "%,f\n", 12345.12345);
        System.out.printf("Using e (floating-point format, scientific notation) for 12345.12345 will display: " + "%e\n", 12345.12345);
        System.out.printf("Using ,(f (negative floating-point option) for -12345.12345 will display: " + "%,(f\n", -12345.12345);
        System.out.printf("Using ,.3f (floating-point with commas format, restrict to 3 decimals) for 12345.12345 will display: " + "%,.3f\n", 12345.12345);
        System.out.printf("Using .2f (floating-point format, restrict to 2 decimals) for -12345.12345 will display: " + "%.2f\n", -12345.12345);
        System.out.printf("Using ,15.4f (floating-point with commas format, specified width, restrict to 4 decimals) for 12345.12345 will display: " + "%,15.4f\n", 12345.12345);
        System.out.printf("Using 3.3f (floating-point format, specified --too short-- width, restrict to 3 decimals) for 12345.12345 will display: " + "%3.3f\n", 12345.12345);
  }
}

Sample Output:
Display numeric values using different format specifiers with printf.
=====================================================================
Some formats for integers:
--------------------------
Using d (decimal format) for 5 will display: 5
Using +d (decimal signed format) for 5 will display: +5
Using (d (negative decimal option) for -5 will display: (5)
Using  4d (decimal, specified width) for 5 will display:    5
Using 04d (decimal, specified width, padding with 0s) for 5 will display: 0005

Some formats for floating-point numbers:
----------------------------------------
Using f (default floating-point format) for 12345.12345 will display: 12345.123450
Using ,f (floating-point with commas format) for 12345.12345 will display: 12,345.123450
Using e (floating-point format, scientific notation) for 12345.12345 will display: 1.234512e+04
Using ,(f (negative floating-point option) for -12345.12345 will display: (12,345.123450)
Using ,.3f (floating-point with commas format, restrict to 3 decimals) for 12345.12345 will display: 12,345.123
Using .2f (floating-point format, restrict to 2 decimals) for -12345.12345 will display: -12345.12
Using ,15.4f (floating-point with commas format, specified width, restrict to 4 decimals) for 12345.12345 will display:     12,345.1235
Using 3.3f (floating-point format, specified --too short-- width, restrict to 3 decimals) for 12345.12345 will display: 12345.123


Additional Resources:
1. (Sun) Java API specifications: http://download.oracle.com/javase/6/docs/api/
2. (Sun) Java API specifications - (java.util) class Scanner http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html
3. (Sun) Java API specifications - class PrintStream  http://download.oracle.com/javase/6/docs/api/java/io/PrintStream.html


References:
[1] Building Java Programs: A Back to Basics Approach, by Stuart Reges, and Marty Stepp, Addison Wesley, 2008.
[2] Java Programming: From Problem Analysis to Program Design, by D.S. Malik, Thomson Course Technology, 2008