Java Reference
In-Depth Information
Although it may seem that we have lost sight of the fact, all these method definitions
must be inside of some class definition. Java does not have any stand-alone methods
that are not in any class. Display 4.2 rewrites the class given in Display 4.1 but this
time we have added a more diverse set of methods. Display 4.3 contains a sample
program that illustrates how the methods of the class in Display 4.2 are used.
TIP: Any Method Can Be Used as a
void
Method
A method that returns a value can also perform some action besides returning a value.
If you want that action, but do not need the returned value, you can invoke the
method as if it were a
void
method and the returned value will simply be discarded.
For example, the following contains two invocations of the method
nextLine()
,
which returns a value of type
String
. Both are legal.
Scanner keyboard =
new
Scanner(System.in);
. . .
String inputString = keyboard.nextLine();
. . .
System.out.println("Press Enter to continue with program.");
keyboard.nextLine();
//Reads a line and discards it.
■
Display 4.2
A Class with More Methods
(part 1 of 2)
The significance of the modifier
private
is discussed in the subsection “
public
and
private
Modifiers” in Section 4.2
a bit later in this chapter.
1
import
java.util.Scanner;
2
public class
DateSecondTry
3 {
4
private
String month;
5
private int
day;
6
private int
year;
//a four digit number.
7
public void
writeOutput()
8 {
9 System.out.println(month + " " + day + ", " + year);
10
}
11
public void
readInput()
12
{
13
Scanner keyboard =
new
Scanner(System.in);
14
System.out.println("Enter month, day, and year.");
15
System.out.println("Do not use a comma.");
16
month = keyboard.next();
17
day = keyboard.nextInt();
18
year = keyboard.nextInt();
19
}