Programming and Problem Solving with Java

(やまだぃちぅ) #1
2.2 Application Construction | 71

We have already shown the template for a field declaration, so let’s look at the declara-
tion of a method. A method declaration consists of the method heading and its body, which
is delimited by left and right braces. The following syntax template represents the declara-
tion of a void method (the kind that mainmust be). We examine the declaration of value-re-
turning methods later in this chapter.


Here’s an example of an application with just one method, the mainmethod. Note that
the programmer selects the name for the application class; we chose PrintName. Because an
application is a class, we begin the name with an uppercase P.


//**
// PrintName application
// This application inputs a name and prints it in two different formats
//**
importjava.io.*; // Package for stream readers
public classPrintName
{
public static voidmain(String[] args) throwsIOException
{
String first; // Person’s first name
String last; // Person’s last name
String middle; // Person’s middle initial
String firstLast; // Name in first-last format
String lastFirst; // Name in last-first format
BufferedReader in; // Input stream for strings


in = new BufferedReader(new InputStreamReader(System.in));
System.out.print(“Enter first name: “); // Prompt for first name
first = in.readLine(); // Get first name
System.out.print(“Enter last name: “); // Prompt for last name
last = in.readLine(); // Get last name
System.out.print(“Enter middle initial: “); // Prompt for middle initial
middle = in.readLine(); // Get middle initial
firstLast = first + “ “+ last; // Generate first format
System.out.println(“Name in first-last format is “+ firstLast);
lastFirst = last +“, “+ first +“, “; // Generate second format
System.out.println(“Name in last-first-initial format is “+
lastFirst + middle + “.”);
}
}


Modifiers void Identifier ( Parameter List )

Statement...

Method-Declaration

{

}
Free download pdf