Tải bản đầy đủ (.pdf) (20 trang)

Java Programming for absolute beginner- P4 ppt

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (528.85 KB, 20 trang )

//The value of b will be 1.
//The addition happens first because of the parentheses
//Next the division and then the subtraction.
int b = 10 - (4 + 14) / 2;
System.out.println(“10 - (4 + 14) / 2 = “ + b);
//The value of c will be -1
int c = 10 - (4 + 14 / 2);
System.out.println(“10 - (4 + 14 / 2) = “ + c);
}
}
38
J
a
v
a
P
r
o
g
r
am
m
i
n
g
f
o
r t
h
e A
b


s
o
l
ut
e B
e
gi
n
n
e
r
FIGURE 2.5
This demonstrates
how parentheses
affect operator
precedence.
Getting Simple User Input
Thus far, the programs you have written have been one-sided in that they per-
form specific tasks and do not accept any user input. Every time you run these
programs the output is exactly the same, making them all but useless in the eyes
of a user after the first few times they are run. How can you make procedures
more dynamic? By adding the functionality to accept and use user input. Any-
time the user runs the application, he or she can enter different input, causing
the program to have the capability to have different output each time it is run.
Because programmers write programs in the real world to be useful to users, this
almost always means that the programs provide some interface that accepts user
input. The program then processes that input and spits out the result. Accepting
command-line input is a simple way to allow users to interact with your pro-
grams. In this section, you will learn how to accept and incorporate user input
into your Java programs. What follows is a listing of the

HelloUser application:
JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 38
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
/*
* HelloUser
* Demonstrates simple I/O
*/
import java.io.*;
public class HelloUser {
public static void main(String args[]) {
String name;
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print(“\nWhat is your name? “);
try {
name = reader.readLine();
System.out.println(“Hello, “ + name + “!”);
}
catch (IOException ioe) {
System.out.println(“I/O Exception Occurred”);
}
}
}
As you can see in Figure 2.6, the program prints a message asking for the user’s
name. After that the cursor blinks awaiting user input. In Figure 2.7 you see that
the user entered her name, “Roseanne” and the application read it in and then
printed
“Hello, Roseanne!”
39

C
h
a
p
t
e
r 2 V
a
r
i
a
b
l
e
s,
D
a
t
a
T
y
p
e
s
,a
n
d
S
i
m

p
l
e
I
/
O
FIGURE 2.6
The user is
prompted for his or
her name, which is
accepted through
standard input.
JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 39
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Using the BufferedReader Class
Unfortunately, getting simple user input is not very straightforward. One might
think it would make sense that the syntax for reading a line would be as simple
as writing a line of output. However, this is not the case. As you know, writing
standard output can be done like this:
System.out.println(“Shampoo is better!”);
So, it would be natural to think reading input could be done like this:
System.in.readln();
But it is not that simple. First you must import the java.io package, which pro-
vides functionality for system input and output:
import java.io.*;
A package is a group of complimentary classes that work together to provide a
larger scale of functionality. This is the second Java program you’ve written that
uses the
import statement. In the HelloWeb applet from Chapter 1, you imported

the
java.awt.Graphics class, which is part of the java.awt package. The differ-
ence here is that you use an asterisk to signify that you might be interested in all
the classes that the
java.io package groups together. Basically, you are import-
ing the
java.io package here to give your program the capability to call upon the
I/O functionality. Specifically, it allows you to use the
BufferedReader and Input-
StreamReader
classes in your program. At this point, you don’t need to under-
stand anything about these classes except that
InputStreamReader reads the
user’s input and
BufferedReader buffers the input to make it work more effi-
ciently.
You can think of a buffer as sort of a middle man. I hear the Corleone family had
a lot of buffers. When reading data in, a program has to make a system call,
which can take a relatively long time (in computer-processing terms). To make up
for this, the buffering trick is used. Instead of making a system call each time you
40
J
a
v
a
P
r
o
g
r

am
m
i
n
g
f
o
r t
h
e A
b
s
o
l
ut
e B
e
gi
n
n
e
r
FIGURE 2.7
The program says
hello to the user
after she enters her
name.
JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 40
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

need a piece of data, the buffer temporarily stores a chunk of data before you ask
for it using only one system call. The buffer is then used to get data for subse-
quent requests because accessing memory is much faster than using a bunch of
system calls.
Inside the
main() method, you declared two variables:
String name;
BufferedReader reader;
Neither of them is a primitive data type. They are both instances of classes. The
name variable is declared to be a String, giving it the capability to hold strings,
which are covered in the next section, and
reader is declared to be a Buffere-
dReader
, giving it the functionality to buffer input. The next line basically speci-
fies
reader to be a standard input buffer:
reader = new BufferedReader(new InputStreamReader(System.in));
In this program you used a slightly different approach to printing a line of output.
You used the
System.out.print() method instead of the System.out.print-
ln()
method. What’s the difference? The System.out.println() method prints
a message to the screen and then adds a carriage return to the end of it. The
System.out.print() method does not add a carriage return to the end of the
output line. As you see in Figures 2.6 and 2.7, the computer prompts the user for
his or her name and the user types the name on the same line as the prompt. It is
also important to note that you used a newline character escape code
\n within
the string passed to
System.out.print() method. This moves the cursor down

one line before printing the message.
After you have instantiated the BufferedReader object, which you have stored in
the
reader variable, it can be used to accept user input. This line of code is what
prompts the user.
name = reader.readLine();
Confused? That’s okay if you are. The important thing here is that you learn the
syntax for accepting user input. Bear with me, this concept, as well as others,
become clearer later on. You’ll use this method of obtaining simple user input in
these early chapters to create command prompt-based games until you learn
graphic user interface (GUI) programming later.
Handling the Exceptions
Although exception handling is covered in more detail later in this book, I feel
that I should explain the basics of it here because you are required to handle
exceptions in this application. Exceptions are encountered when code does not
HINT
41
C
h
a
p
t
e
r 2 V
a
r
i
a
b
l

e
s,
D
a
t
a
T
y
p
e
s
,a
n
d
S
i
m
p
l
e
I
/
O
JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 41
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
work as it is expected to. Exception handling is used to plan a course of action in
the event your code does not work as you expect it to. Here is an analogy to help
you digest this concept. You have to go to work or school every normal weekday,
right? Well, what if there is a blizzard or a tornado and you cannot go to work?

In this analogy, the blizzard or tornado is the exception because it is an abnor-
mality. The way this exception is handled is that you end up staying home from
work.
Java requires that exceptions be handled in certain situations. In the
HelloUser
application, you are required to handle an IOException (input/output exception).
What if you never actually get the user’s input here? This would be an exception
and you would not be able to incorporate the user’s name in the program’s out-
put. In the case of this application, you issue an error message, indicating that
an exception was encountered. You do not say “Hello” to the user—you can’t
because you were not able to retrieve the user’s name.
You handled exceptions in the
HelloUser application by using the try…catch
structure. Any code, such as reading user input that might cause an exception, is
placed within the
try block, or “clause”. Remember that a block is one or more
statements enclosed within a set of curly braces:
try {
name = reader.readLine();
System.out.println(“Hello, “ + name + “!”);
}
Here, you are trying to read user input and use it in a standard output line. What
if it doesn’t work? That’s what the
catch clause is for:
catch (IOException ioe) {
System.out.println(“I/O Exception Occurred”);
}
If the code within the try clause does not work as it is expected to—there is an
IOException— the code within the catch clause is executed. In this case the error
message

“I/O Exception Occurred” is printed to standard output to let the users
know that a problem was encountered. In the real world, you try to handle
exceptions as gracefully as you can. When detecting exceptions, you should try
to handle them in a way so that your program uses default values instead of halt-
ing abruptly, but in some instances, your program just can’t continue due to
some error that you can’t provide a work-around for. In these cases, you should
at the very least, try to generate meaningful error messages so that users can use
them to resolve any possible problems on their end.
42
J
a
v
a
P
r
o
g
r
am
m
i
n
g
f
o
r t
h
e A
b
s

o
l
ut
e B
e
gi
n
n
e
r
JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 42
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
The Math Game
In this section you incorporate much of what you’ve learned so far into a single
application. After you write and compile this application, you can actually use it
as a tool to remind yourself how arithmetic operators work in Java. Here is a list-
ing of the source code for
MathGame.java:
/*
* MathGame
* Demonstrates integer math using arithmetic operators
*/
import java.io.*;
public class MathGame {
public static void main(String args[]) {
int num1, num2;
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(System.in));
try {

System.out.print(“\nFirst Number: “);
num1 = Integer.parseInt(reader.readLine());
System.out.print(“Second Number: “);
num2 = Integer.parseInt(reader.readLine());
reader.close();
}
// Simple Exception Handling
catch (IOException ioe) {
System.out.println(“I/O Error Occurred, using 1 ”);
num1 = num2 = 1;
}
catch (NumberFormatException nfe) {
System.out.println(“Number format incorrect, using 1 ”);
num1 = num2 = 1;
}
//Avoid this pitfall e.g. 1 + 1 = 11:
//System.out.println(num1 + “ + “ + num2 + “ = “ + num1 + num2);
System.out.println(num1 + “ + “ + num2 + “ = “ + (num1 + num2));
System.out.println(num1 + “ - “ + num2 + “ = “ + (num1 - num2));
System.out.println(num1 + “ * “ + num2 + “ = “ + (num1 * num2));
System.out.println(num1 + “ / “ + num2 + “ = “ + (num1 / num2));
System.out.println(num1 + “ % “ + num2 + “ = “ + (num1 % num2));
}
}
43
C
h
a
p
t

e
r 2 V
a
r
i
a
b
l
e
s,
D
a
t
a
T
y
p
e
s
,a
n
d
S
i
m
p
l
e
I
/

O
JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 43
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Parsing Strings to Numbers
Most of the code in the MathGame application should already be familiar to you.
The code that is new to you is the code that parses a string value into an integer
value:
Integer.parseInt(reader.readLine());
Parsing, just like casting, is changing the data type of the value of a variable or lit-
eral. The
BufferedReader.readLine() method accepts the users input in string
form. You cannot assign strings to
int variables or perform mathematical opera-
tions on them, so you must first convert them to numbers. For instance, you
can’t do this:
int myNumber = “8”;
An int variable can only store a valid int value, but in the line above “8” is
expressed as a
String literal, not an int. Because you need to accept user input
here in string form, you need a way to parse the
String input to an int. Inte-
ger.parseInt()
does this. It is a method defined within the Integer class. It
accepts a
String argument and returns the int value of that string. For example
if the
String literal “8” is passed to this method, it returns the int 8. Here are
some useful methods for converting strings to numbers:
Byte.parseByte(String s) Converts a string to a byte.

Short.parseShort(String s) Converts a string to a short.
Integer.parseInt(String s) Converts a string to an int.
Long.parseLong(String s) Converts a string to a long.
As shown in Figure 2.8, this program prompts the user for two integers and then
performs arithmetic operations on them. It displays the results of these opera-
tions to the user. It’s not exactly a game, unless math is fun for you, but you get
the point.
44
J
a
v
a
P
r
o
g
r
am
m
i
n
g
f
o
r t
h
e A
b
s
o

l
ut
e B
e
gi
n
n
e
r
FIGURE 2.8
The MathGame
application
demonstrates
mathematical
operations applied
to integers.
JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 44
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
45
C
h
a
p
t
e
r 2 V
a
r
i

a
b
l
e
s,
D
a
t
a
T
y
p
e
s
,a
n
d
S
i
m
p
l
e
I
/
O
Float.parseFloat(String s) Converts a string to a float.
Double.parseDouble(String s) Converts a string to a double.
The string passed to a method that parses it to another data type must be a valid
representation of that data type. For example, if you tried to parse the

String
“one” to an integer using Integer.parseInt(), it would cause a
NumberFormatException, however, it is not required that you handle this excep-
tion, although you do in the
MathGame application by simply using the int 1 if
user input isn’t obtained. If you don’t handle the
NumberFormatException, your
program will crash if the user types a value that cannot be parsed to an
int.
The TipCalculator Application
Here is another program for you to take a look at. It uses concepts of the Math-
Game
and TipAdder applications. It prompts the user for the price of the meal,
converts the
String value of the user’s input into a double and then calculates
the tip and displays the information to the user. Take a look at the source code:
/*
* TipCalculator
* Parses user input and does floating point math
*/
import java.io.*;
public class TipCalculator {
public static void main(String args[]) {
String costResponse;
double meal, tip, total;
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print(“\nHow much was the meal? “);
try {
costResponse = reader.readLine();

// Note: we are not handling NumberFormatException
meal = Double.parseDouble(costResponse);
tip = meal * 0.15;
total = meal + tip;
System.out.println(“The meal costs $” + meal);
System.out.println(“The 15% tip is $” + tip);
System.out.println(“The total is $” + total);
reader.close();
}
TRAP
JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 45
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
catch (IOException ioe) {
System.out.println(“I/O Exception Occurred”);
}
}
}
Figure 2.9 shows the output of this program. Notice that this calculation is more
precise than in the
TipAdder program. That’s because you used doubles instead
of
floats. Oh, one more thing, you didn’t handle any of the exceptions. Figure
2.10 shows what happens when you don’t get the
double value you expect.
46
J
a
v
a

P
r
o
g
r
am
m
i
n
g
f
o
r t
h
e A
b
s
o
l
ut
e B
e
gi
n
n
e
r
FIGURE 2.9
The output of the
TipCalculator

application.
FIGURE 2.10
Oops, my program
crashed! I didn’t
type a valid
double
value.
Accepting Command-Line Arguments
As mentioned in Chapter 1, it is possible to pass command-line arguments to
your application. Command-line arguments are parameters that are passed to the
program when it is initially started up. This is done, as you’d imagine, from the
JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 46
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
command prompt. You pass parameters to an application by using the following
syntax when running the application:
java ApplicationName command_line_arguments
When using a Macintosh, you will be prompted for any command-line arguments
when you run your application. Command-line arguments are passed to the
main() method as its only parameter: String args[]. It is an array (list) of para-
meters, so you can handle it like any other array. You learn about arrays in the
next chapter. For now, you can just write the following application to give your-
self a basic idea of how Java can accept and use command-line arguments.
/*
* HelloArg
* Uses command-line arguments
*/
public class HelloArg {
public static void main(String args[]) {
System.out.println(“Hello, “ + args[0] + “!”);

}
}
As you can see in Figure 2.11, I ran this procedure three times using different
command-line arguments causing the application to issue different output. By
the way, I wouldn’t make the last guy angry, you wouldn’t like him very much if
he gets angry.
47
C
h
a
p
t
e
r 2 V
a
r
i
a
b
l
e
s,
D
a
t
a
T
y
p
e

s
,a
n
d
S
i
m
p
l
e
I
/
O
INTHEREAL WORLD
Command-line arguments are used for a number of different purposes in the
real world. They are used as parameters that affect the way the program runs.
Command-line arguments can exist to allow the user certain options while run-
ning your program. One other major use of command-line arguments from a
programmer’s standpoint is to aid in debugging or testing your code. You can
use a command-line argument to set some sort of debug-mode parameter. With
this debug mode set, you can debug your code by giving yourself special
options that would not normally be available. For example, say you are a video
game programmer. You need to test a particular game level, but it is a particu-
larly difficult level for you to get through or would be time consuming. You can
use a command-line argument that gives you access to any position in any level
of the game you’re programming, so you can just test the parts you need to.
JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 47
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Arguments are separated by spaces. Make sure that if an argument needs to

include spaces, you surround the argument with double quotation marks.
Otherwise, it will be broken into multiple arguments and your application will
not run as you intended it to.
Strings and String Operations
A string is a sentence, or a succession of characters strung together. You already
used strings in every program you’ve written to this point (remember
“Hello,
world!”
and “\nFirst number: “). Now you learn about strings in more detail.
You learn about the
String class, and its operations and methods.
The String Class
A string is not a primitive data type. It is a class of its own. The String class
includes methods for examining and operating on its individual characters. It
also has methods for searching strings, for comparing them, concatenating them
(appending one string to another), for extracting substrings (smaller segments of
strings) and for converting alphabetical characters from uppercase to lowercase
(or visa versa). It also has methods for converting other data types into string
values.
Java treats all string literals as
String objects. String literals are always sur-
rounded by quotation marks. That’s how Java knows they’re strings and not vari-
able names or some other Java code. An object is an instance of a particular class.
Any operations that you can perform with
String objects stored in variables can
also be performed with
String literals. Here is an example using the
String.charAt() method. This method will return the char at a particular index
of the
String. The index of a string is a number that represents a character’s posi-

tion within the string, starting with
0. To put it another way, the index of the
TRAP
48
J
a
v
a
P
r
o
g
r
am
m
i
n
g
f
o
r t
h
e A
b
s
o
l
ut
e B
e

gi
n
n
e
r
FIGURE 2.11
Passing command-
line arguments to
the
HelloArg
application.
JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 48
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
first character in a String is 0, the index of the second character is 1, the next
index is 2 and so on until the last character in the string. The index of the last
character is one less than the total length of the
String.
//Create a String Object
String str = “Cranberry”;
//the next two lines of code do basically the same thing
char strChar = str.charAt(4);
char cranChar = “Cranberry”.charAt(4);
Both variables strChar and cranChar will have the value b because that is the
value of the
char at index 4 (the fifth letter of Cranberry).
Notice that in this program and in some other programs you’ve written that you
used the
+ operator to “add” strings together. This operator works differently
when used on strings. Adding substrings together to form larger strings is called

concatenation. It’s a pretty big word for something so simple, isn’t it? An example
of this is as follows:
String dogsName = “Mario “ + “Don Cagnolino”;
The value “Mario Don Cagnolino“ is assigned to the dogsName variable. Note that
I put a space after
“Mario“ in the first substring. If I didn’t do that, the value
would have been
“MarioDon Cagnolino“. In the real world, concatenation is used
to build strings from multiple sources, just like you did in the
HelloArg program.
You concatenated the string literal,
“Hello, “ with the string value stored in
args[0], and then concatenated the exclamation point. args[0] can be any
string, so you add it to the hard-coded literal that you always want to print,
“Hello, “ to build the string you want to print. FYI: the term hard-coded refers
to values directly written into program code that don’t depend on any run-time
value.
String Methods
The final project in this chapter uses String methods to manipulate the user’s
name. The
String method includes quite a few useful methods used to operate
on strings or to parse other data types to strings. Table 2.6 describes some of the
useful methods defined within the
String class.
Getting Back to the Name Game
The NameGame application introduced at the beginning of this chapter uses some
String methods to play around with the user’s name. Now that you’re almost at
the end of the chapter and have already learned so much about the Java language,
49
C

h
a
p
t
e
r 2 V
a
r
i
a
b
l
e
s,
D
a
t
a
T
y
p
e
s
,a
n
d
S
i
m
p

l
e
I
/
O
JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 49
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
you should be able to understand the source code. Try writing this application
and running it:
/*
* NameGame
* Joseph P Russell
* Demonstrates Simple I/O and String Methods
*/
50
J
a
v
a
P
r
o
g
r
am
m
i
n
g

f
o
r t
h
e A
b
s
o
l
ut
e B
e
gi
n
n
e
r
Method Description
char charAt(int index) Returns the character at the specified index.
String concat(String str) Concatenates this string with another and
returns the result.
Boolean endsWith(String str) Tests whether this string ends with the suffix
str.
boolean equals(String str) Compares this string to another and returns
true if they’re equal.
boolean equalsIgnoreCase(String str) Tests whether this string equals str, ignoring
case.
int indexOf(char c) Returns the integer index of char c at its first
occurrence.
int indexOf(char c, int n) Returns the first index of c starting at index n.

int indexOf(String str) Returns the index of the first occurrence of
str.
int indexOf(String str, int n) Returns the index of the first occurrence of
str starting at index n.
int length() Returns the length (number of characters) of
this string.
String replace(char c1, char c2) Replaces all occurrences of c1 with c2 and
returns the result.
String substring(int n1, int n2) Returns the substring of this string between
index
n1 and n2.
String toLowerCase() Converts all letters in this string to lowercase.
String toUpperCase() Converts all letters in this string to uppercase.
String valueOf() Converts the argument to a string. There are
versions of this method that accept
boolean,
char, double, float, int, and long data
types.
TABLE 2.6 SOME
S
TRING
C LASS M ETHODS
JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 50
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
import java.io.*;
public class NameGame {
public static void main(String args[]) {
String firstName = ““;
String lastName = ““;

String fullName;
String initials;
int numLetters;
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print(“What is your first name? “);
try {
firstName = reader.readLine();
}
catch (IOException ioe) {
System.out.println(“I/O Exception Occurred”);
}
System.out.println(“That’s a nice name, “ + firstName + “!”);
System.out.println(“I’ll shout it! “ + firstName.toUpperCase() + “!”);
System.out.print(“OK, what’s your last name? “);
try {
lastName = reader.readLine();
}
catch (IOException ioe) {
System.out.println(“I/O Exception Occurred”);
}
fullName = firstName;
//alternative to using the ‘+’ operator
fullName = fullName.concat(“ “).concat(lastName);
System.out.println(“Oh, so your full name is “ + fullName + “.”);
System.out.println(“Or sometimes listed “
+ lastName + “, “ + firstName + “.”);
initials = firstName.charAt(0) + “.” + lastName.charAt(0) + “.”;
System.out.println(“Your initials are “ + initials);
numLetters = firstName.length() + lastName.length();

System.out.println(“Did you know there are “
+ numLetters + “ letters in your name?”);
System.out.println(“Bye!”);
}
}
51
C
h
a
p
t
e
r 2 V
a
r
i
a
b
l
e
s,
D
a
t
a
T
y
p
e
s

,a
n
d
S
i
m
p
l
e
I
/
O
JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 51
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
When you run this program it should look similar to Figure 2.1. Try running this
program using different names to see how this program’s output can be differ-
ent each time. Here’s an explanation of how this program works. Variables
firstName and lastName are strings that are used to hold the user’s first and last
names. They are initialized to the null string (
““). You must do this because
accepting user input can possibly cause an exception. If it does, these strings will
remain uninitialized and the compiler checks for this and forces you to initialize
it outside of the
try block before you access these variables’ values. fullName is a
string that holds the user’s full name,
initials holds the user’s initials, and num-
Letters
is an int that holds the number of letters in the user’s name. The last
variable

reader is a BufferedReader that is used to accept the user’s input.
When the program starts, it prints “
What is your first name?”. Remember, you
use the
System.out.print() method so that you can accept user input on the
same line as the prompt because it doesn’t append a newline character to the end
of the string. Next, you use the
reader object to read in the user’s first name and
print some output using the name the user entered. You use the
String.toUp-
perCase()
method to convert the name to uppercase:
System.out.println(“I’ll shout it! “ + firstName.toUpperCase() + “!”);
Next, you prompt for and accept the user’s last name. Now that you have the first
and last name, you can use them to build the full name. The lines of code that
do this deserve an explanation:
fullName = firstName;
fullName = fullName.concat(“ “).concat(lastName);
First, you assign the first name to fullName. Then you concatenate a space and
the last name. Here I wanted to demonstrate how you can use the string returned
by the
String.concat() method to call a string method. fullName.concat(“ “)
returns the string value of the first name with a space appended to the end of it.
This value is returned as a string object, so you can use it to call string methods.
Here you did this by using a dot right after the first method call and then called
the
String.concat() method again to append the last name. You can also write
it this way to make it more readable, it does the same thing:
FullName = firstName.concat(“ “ + lastName);
You get the user’s initials using the firstName.charAt(0) and

lastName.charAt(0). To count the number of letters in the user’s name, you
added
firstName.length() to lastName.length(). Remember that this method
returns the total number of characters in the string, but the character index
starts at
0. This means that if you wanted to get the last character in the user’s
full name, you do it this way:
fullName.charAt(fullName.length() – 1).
52
J
a
v
a
P
r
o
g
r
am
m
i
n
g
f
o
r t
h
e A
b
s

o
l
ut
e B
e
gi
n
n
e
r
JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 52
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Summary
You have learned a lot in this chapter. You learned how to write a Java application
and a simple Java applet. You learned about variables and data types and how to
use them in your applications. You also learned how to obtain simple user input
and how to create interactive applications. You learned how to handle numerical
values in Java and perform arithmetic operations on them. You were also intro-
duced to some more advanced topics such as event handling and object-oriented
programming. Don’t worry if you don’t understand it all yet. It’s a lot to absorb.
You will continue to build upon what you already know about Java in the chap-
ters to come. In the next chapter, you learn how to generate random numbers
and conditional statements, and to work with arrays.
53
C
h
a
p
t

e
r 2 V
a
r
i
a
b
l
e
s,
D
a
t
a
T
y
p
e
s
,a
n
d
S
i
m
p
l
e
I
/

O
CHALLENGES
1. Write an application that calculates a 5% tax for any given price and dis-
plays the total cost.
2. Write an application that prints the multiplication table for integers 1
through 12.
3. Write an application that accepts a number from the user and prints its mul-
tiplication table values (multiply it by 1 through 12 and print the results).
4. Write an application that reads in a user’s sentence of unknown, possibly
mixed upper- and lowercase letters, capitalizes the first letter of the sen-
tence, makes all other letters lowercase, and makes sure there is a period
at the end.
5. Write an application that searches for your first name in a string and
replaces it with your last name.
JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 53
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
This page intentionally left blank
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
So far, all the programs in this book have been predictable.
Every time they run, they do exactly the same thing. They
vary only based on user input or command-line arguments.
How cool would it be to be able to write a program so that
even you can’t predict its output each time you run it? In this
chapter you learn how to generate random numbers and use
them to add a level of unpredictability to your programs. You
will use random numbers in real-world projects to create
games that have replay value, as they run differently each
time you play them. You also learn to dynamically branch the

flow of your programs based on certain conditions that you
can test for. You learn about arrays and understand how to
use them in your Java programs.
Arrays are used in real-world programming to collect data of
a single type together in a list. For example, say you’re writ-
ing a retail cash register program. You would want to keep
T
h
e
F
o
r
t
u
n
e
T
e
l
l
e
r
:
R
a
n
d
o
m
N

u
m
b
e
r
s,
C
o
n
d
i
t
i
o
n
a
l
s,
a
n
d
A
r
r
a
y
s
3
CHAPTER
JavaProgAbsBeg-03.qxd 2/25/03 8:49 AM Page 55

TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
track of the purchase item prices separately so you could print them all out as indi-
vidual lines on the receipt. It would be ridiculous to have an instance variable for
each item, right? Instead, you could store all of the prices in a list by using a
double
type array. Once you have the list of prices, you can list them individually and total
them up at the end, using just one variable name. At the end of the chapter, you put
these topics together in one single project. In this chapter, you will
• Generate random numbers using Math.random() and java.util.Random
• Use the if statement
• Use the switch statement
• Use the ternary operator (? :)
• Declare, initialize, and iterate arrays
The Project: the Fortune Teller
The final project of this chapter is the FortuneTeller application. You can see the
final project in Figure 3.1.
56
J
a
v
a
P
r
o
g
r
am
m
i

n
g
f
o
r t
h
e A
b
s
o
l
ut
e B
e
gi
n
n
e
r
FIGURE 3.1
The Great Randini
predicts tomorrow.
When you run this application, your fortune is read for tomorrow. Each time you
run it, you’ll see a different fortune. The exact output is not predictable. Maybe
the Great Randini can predict it, but unless you’re psychic, you cannot. It is
JavaProgAbsBeg-03.qxd 2/25/03 8:49 AM Page 56
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
impossible for you to create this application using only the techniques you
learned in the first two chapters, so read on young padawan!

Generating Random Numbers
In this section, you learn about the Math class and how you can use it to generate
random numbers. You also take a look at other ways to use the
Math class to call
upon mathematical functions. Another class that you learn about is the
Random
class. You learn how to use this class as an alternative way to generate random
numbers.
The NumberMaker Application
The NumberMaker application demonstrates how to generate a random double and
assign that value to a variable. It’s very straightforward to program. Here is a list-
ing of the source code:
/*
* NumberMaker
* Generates random numbers
*/
public class NumberMaker {
public static void main(String args[]) {
double randNum = Math.random();
System.out.println(“Random Number: “ + randNum);
}
}
There is one line here that you should be unfamiliar with:
double randNum = Math.random()
In this line, you declare randNum as a double and assign a random number to it.
You do this by calling the
Math.random() method, which returns a random num-
ber (as a
double). The values range from 0.0 (inclusive) to 1.0 (exclusive). Inclusive
means that the lower limit,

0.0, is included as a possible value, whereas exclusive
means that
1.0, as the upper limit, is only a cap and is not a possible value.
Another way to state this is that the range of possible values are all the values
that are greater than or equal to
0.0 and less than 1.0. This program just spits
out the random number and doesn’t really have any use for it except to show how
to generate random numbers. Run it a few times, as in the example in Figure 3.2.
Your output should be different each time, as was mine.
57
C
h
a
p
t
e
r 3 T
h
e
F
o
r
t
u
n
e
T
e
l
l

e
r
:
R
a
n
d
o
m
N
u
m
b
e
r
s,
C
o
n
d
i
t
i
o
n
a
l
s,
a
n

d
A
r
r
a
y
s
JavaProgAbsBeg-03.qxd 2/25/03 8:49 AM Page 57
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

×