Sie sind auf Seite 1von 50

Chapter 5.

Array and Strings

Context

The purpose of this unit is to investigate array data structures and string objects.

Objectives

Having successfully completed this unit you should be able to:

 Explain the difference (and similarities) between strings and arrays of characters.
 Declare an array, define, interrogate and change individual elements of an array.
 Declare and work with instances of the String class.
 Implement Java programs illustrating the manipulation of arrays and strings.

Study Planning

You should expect to spend approximately 9 hours studying this unit. You may find it
convenient to break up your study as follows:

Disk-based Content: 2¼ hours


Application: 3 hours
Set textbook Content: 1 hour
Reflection (On-line discussions, review questions): 1 hour
Tutorial Work: 1 hour
Related Coursework: ¼ hour
Extension Work: ½ hour

Equipment/software required

 Sun Java 2 Platform (also know as Java Development Kit 1.3)


 TextPad 4.5
 A Web browser

Reading material and resources


Core texts (supplied with module material):

1. Java: how to program. H. M. Deitel and P. J. Deitel, 3rd edition, Prentice-Hall, ISBN:
0-13-012507-5

Online Resources:

1. Frequently-asked questions
2. Additional Source Code Examples

Introduction to Unit 5

The unit introduces two important Java programming concepts:

 arrays
 string objects — instances of the String class

As with the previous unit, the concepts in this unit are not all explicitly about object-
oriented programming. However, such concepts as arrays of objects, and objects of the
String class illustrate how the concepts introduced in this unit are important for working
with different kinds of non-primitive variable types, and also for the implementation of
methods that process each member of an array.
The sequence of the topics in this unit is by design — you will understand strings much
easier if you have grasped the concepts of Java character arrays first.

Both of these concepts are related, since the words (and the spaces between them) below
could be represented either as an array or an instance of the String class:

this is a sequence of characters


As you will discover working through this unit, we could declare an array of characters
and initialise this array variable as follows:
char sentence = {'t', 'h', 'i', 's', ' ', 'i', 's', ... }
Or we could declare and initialise an instance of the String class to contain the sentence
as follows:
String sentence = "this is a sequence of characters";
As can be seen above, arrays are designed around the individual values stored in them
(i.e. each character is treated separately), while a String object stores and processes
complete sequence of characters. However, String objects can only be used with
characters, while arrays can be used to store organised collections of any type of value
(character, objects, primitive types).

Arrays — Assigned reading


Read section 7.1-7.4 pp 269-282 of Chapter 7 Deitel and Deitel

What is an array?

An array is a way of storing, retrieving and changing a sequence (i.e. ordered collection)
of variables that are all the same type. An array has an identifier (name), stores elements
all of the same type, and has an unchanging size (dimension).

The figure below illustrates an array deliveries, which stores 5 elements, each of type int.
Each element of the array represents how many deliveries were made by a courier in a
working week.

deliveries[]

element value
deliveries[0] 14

deliveries[1] 17

deliveries[2] 22

deliveries[3] 9

deliveries[4] 16

Notice how each of the 5 variables stored in this array (the 5 elements of the array) are
referred to by a combination of the array identifier and the element number (index) inside
square brackets. Also notice how the first element of the array has index 0, rather than 1.
Forgetting this feature of arrays leads to many simple errors when learning to use them.
To declare an array, one must state the type of variables that will be stored within it, and
the identifier of the array.

Imagine we are developing a software system for a restaurant, and we need to be able
to store the number of people who have pre-booked for each evening. For example, if we
wish to store all the bookings for the coming week, we need to store and work with 7
intvariables. Rather than have seven different variables, we can work with an array of 7
intvariables. We shall call this array bookings. For example, the following line:

int bookings[];
declares an array with the identifier bookings, that can refer to a sequence of
intvariables.

Once declared, an array needs to have its size defined. For example, we can define our
bookingsarray to store 7 intvariables as follows:
bookings = new int[7];
To refer to a particular element (variable) in an array, we need to specify the array
identifier and the index of the array element in which we are interested. So, for example
we display the first booking as follows:

System.out.println( booking[0] );

Motivation for using arrays

Here is an example of the use of an array. Suppose a program performs calculations on


sales totals recorded each month. To store the monthly totals we could define a variable
for each month like this:

double januarySales;
double februarySales;
//...
double decemberSales;
All the monthly totals can be added together to give an annual total like this:
double annualSales = januarySales + februarySales + marchSales +
aprilSales
+ /* other months */ + decemberSales;
While this strategy is just about viable when there are twelve variables, what would
happen with, say, 2,000 variables? The program would be extremely long and ugly, and
it would be easy to make a mistake and refer to the wrong variable.

An alternative approach is to define an array to store the monthly totals. There are twelve
months in the year, so we need an array with 12 elements. In Java:

double monthlySales[] = new double[12];


This can be read as "The variable monthlySales is an array of doubles . Make it a new
array of doubles with 12 elements".

Then instead of writing

januarySales = 1234;
februarySales = 2345;
//... etc
We would write
monthlySales[0] = 1234;
monthlySales[1] = 2345;
// ... etc
We have assumed here that January is month number 0, February is number 1, and so
on, up to December which is number 11. This brings out an extremely important point:
array elements in Java are always numbered from 0, not from 1. This means that if
an array has 100 elements, the last element is numbered 99, not 100, as the first is 0, not
1.

This very often causes confusion for novice programmers; if your Java program reports
errors like "arrayBoundsException" then this mistake is very likely to be the cause.
So how do we add the monthly totals to give an annual total now? Here is the Java:

double annualTotal = 0;
for(int i = 0; i < 12; i++)
annualTotal = annualTotal + monthlySales[i];
In this example we aere using a variable to refer to the appropriate array element, that is,
rather than something like :
monthlySales[0]
we am writing:
monthlySales[i]
This means that if i has the value 3, we are then referring to the monthlySales values for
April. In general, as the value of i changes, we can look at the monthly sales figures for
that month (the i'th month). This ability to use a variable to select a particular array
element is an extremely powerful feature, and is found in almost all programming
languages.

Declaring and defining an array

Note the following important points about declaring and defining arrays:

 Declaring an array is stating that an array exists, and that it has a particular name
and data type
 Defining an array is making an array available of a particular size (a particular
dimension)
 The distinction is important, particularly when arrays are passed between
methods.

Declaring arrays

The general form of an array declaration is:

<type> <identifier>;
Examples of array declaration include:
int shoeSizes[];
char initials[];
String names[];
Date appointments[];
All an array declaration does is to state that a particular identifier can refer to an array of
variables of the declared type. No array is set up at this state, just the variable itself. So
we can illustrate this for array initials after declaration as follows:

char initials []
element value
Defining the dimensions of an array

The general form of defining an array dimension is:

<array_identifier> = <type>[<dimension>];
Examples of arrays having their dimension defined include:
intials = new char[3];
appointments = new Date[365];
No values are placed into the array when it is defined, however, an array element is
created to store each variable of the defined type. So, for example, the array initials
after definition of size 3 can be illustrated as follows:

char initials []
element value
initials [0] ''
initials [1] ''
initials [2] ''
We can place values into these array elements with variable assignment statements. So
for example, to place the characters 'I', 'N' and 'T' into this array we could use the following
statements:
initials[0] = 'I';
initials[1] = 'N';
initials[2] = 'T';

Common declaration and definition errors

Two common errors (though easily spotted and debugged) as:

 having a different type when declaring and defining an array


 forgetting the double square brackets "[" "]" when declaring or defining an array

The of these problems is illustrated with the example applet ArrayDefinition below:
import java.applet.Applet;

class ArrayDefinition extends Applet


{
double monthlySales[];

public void init()


{

monthlySales = new int[12];


}
}
When compiled, this applet results in the following output:
The error in this case is that the array monthlySales has been declared as an array of
type double, but when its dimension (size ) 12 is defined, the variable type int has been
written by mistake.
The second common error, forgetting the open and closed square brackets is illustrated
in the program below:
import java.applet.Applet;

class ArrayDeclaration extends Applet


{
double dailyCosts;

public void init()


{

dailyCosts = new double[31];


}
}
The result of trying to compile this program is as follows:
The error in this case is that when declared, the programmer forget to include the double
square brackets. The line:
double dailyCosts;
is valid, but does not declare dailyCosts to be an identifier of an array of double variables
— it simply declares dailyCosts to be the identifier of a one double variable.

Combining declaration and definition

The following Java applet produces an error message when compiled:

import java.applet.Applet;

class SalesArray extends Applet


{
double monthlySales[12];

// methods go here

When compiled, the compiler gives the following error message:


This seems odd at first, since it appears to be a sensible way to tell the Java compiler to
make an array of twelve doubles called monthlySales . However, it won't work because
Java insists on separating declaration and definition of arrays. The following line is OK:
double monthlySales[];
It can be read as "monthlySales is an array of doubles". We can follow this with
monthlySales = new double[12];
Meaning "make monthlySales an array of 12 doubles". These lines could be combined
into one as follows:
double monthlyTotals[] = new double[12];
As you write programs using arrays, these issues should become more natural to you.

The general form for combining the declaration and definition of arrays is as follows:

<type> <identifier> = new <type>[ <dimension> ];

Array size

Java arrays provide a value to tell the program the size (number of elements) an array
has been defined with. If arr is an array (of any type) then arr.length is the length of the
array.

For example, this section of Java:


int arr = new int[100];
System.out.println( arr.length )
Will print the number "100" as there are 100 elements in array arr.
Note that "length" is not a method.
This means that it would be incorrect in this case to write x.length().
This is a cause of some confusion because in the case of the String class
(described below) this would be the correct notation! As ever, it takes a bit
of practice to get it right.

Array index

The number that identifies a particular element in an array is called the index. If the
number is actually a variable, then this is called an index variable. An index must be an
integer (i.e. of type int), because it refers to a particular element in an array — i.e.
element 3 or element 0 or element 2000, never anything like element 2.5!

This Java applet will generate an error message:

import java.applet.Applet;
class ArrayIndex
{
double x[] = new double[100];
public void init()
{
x[0.0] = 100.0;
}
}
The error produced is:
This is because "0.0" (zero point zero) is not the same to the compiler as "0" (zero). "0.0"
is a floating point number, while "0" is an integer.

The following six sets of Java statements all have the same effect: they set the variable
x equal to the 3rd element of the array array1 (don't forget: the third element has index 2,
not 3):

int x = array1[2];

int x = array1[5-3];

int index = 2;
int x = array1[index];

int index = 5;
int x = array1[index - 3];

int index = 5 - 3;
int x = array1[index];

int x = array1 [(int)2.0];

You should look at each of these lines and ensure that you understand why it produces
the result that it does. The last line introduces something you may not have used before:
the use of a data type (in this case int) before an item of a different type (in this case
the number 2.0, which is a double).

As you may recall from a previous unitt, this form of expression is called a cast. It is an
instruction to the compiler to treat evaluate an expression to a value of the stated type —
converting from some other type. In this case, an array index has to be an integer, so we
tell the compiler to treat 2.0 as an integer. What do you think would happen if we said:

int x = y[(int)2.5];
Of course, 2.5 can't be an integer. In fact what happens in this case is that the compiler
chops off the decimal part of the number, and makes it 2.
An aside about casting
You can't use the cast to convert anything to anything else. For example,
the compiler will produce an error message if you try to compile

int x = (int)"hello";
because "hello" simply cannot be converted to an integer.

Looping with the array index

A very common way to process all the elements of an array, is to use a loop variable for
the array index.

The loop variable must start at 0, and go up to the <array>.length value. However, we
must be careful not to attempt to retrieve an element with index of <array>.length , since
array index values go from 0 .. (<array>.length - 1).

For example, to total all the values of a double array purchases, we could write the
following loop, without having to know how the array was defined:

double total = 0;
int index ;

for( index = 0; index < purchases.length; index++)

total = total + purchases[ index ];


First we declare and initialise a double variable total to zero:
int total = 0;
then we declare our int index loop variable index:
int index ;
then we start the loop:
for( index = 0; index < purchases.length; index++)
Let us assume that the double array purchases contains the following:
purchases[]

element value
purchases[0] 10.11

purchases[1] 5.0

purchases[2] 2.5

Then purchases.length is 3, since there are 3 elements in this array.

Our loop, therefore, is evaluated at run time to:

for( index = 0; index < 3; index++)


As the loop iterates the following happens:
index loop condition total =
total + purchases[ index ];

0 0 < 3 = true 0 + purchases[0]


= 0 + 10.11 = 10.11

1 1 < 3 = true 10.11 + purchases[1]


= 10.11 + 5.0 = 15.11

2 2 < 3 = true 15.11 + purchases[2]


= 15.11 + 2.5 = 15.61

3 3 < 3 = false
loop terminates

and the value of total after the loop terminates is 15.61.

Array bounds exceptions

An error will occur if an index is given for an array, which is either negative, or greater
than the index of the last element of the array (i.e. a value of <array>.lengthor greater).
Such an error is called an array bounds exception.

The program must not attempt to read or change the value of an array element that does
not exist. For example, no array can have an element whose index is less than zero

Suppose we define an array of doubles like this:

double myArray[] = new double[100];


Then all the following lines will cause a run time error (that is, the program will compile
correctly, but when executed will stop with an error message):
myArray[] = 0;
myArray[100] = 0;
myArray[1000] = 0;

int y = -1;
myArray[y] = 0;
Note that the compiler does not detect these errors; the error is not noted until the program
is executed. This is true even of the first line, which is manifestly incorrect.
Consider the following application:
class ArrayBoundsException
{
double myArray[] = new double[100];

public static void main( String args[] )


{
ArrayBoundsException app = new ArrayBoundsException();
}

ArrayBoundsException()
{
myArray[-1] = 0;
}
}

The error displayed when this application is run as follows:

Arrays — Activities, Exercises and Review Questions


Activity 1 – Applet to display and total array elements

Activity 2 — Display and highest value of a 'float' array

Activity 3 – Reversing a 'char' array

Exercise 1 — Declaring and Defining arrays

Exercise 2 — Why only run-time array bounds exception errors?

Exercise 3 – Arrays Summary

Exercise 4 – Array Exercises

Strings — Assigned reading

Read section 10.1 - 10.5, 10.11 and 10.13 pp 456-467, 478-477 and 479-481
respectively from Chapter 10 of Deitel and Deitel

Strings — sequences of characters treated as an object

We have already met and used strings. Consider this application program:

class ProgramMessage
{
public static void main( String args[])
{
System.out.println("This application is running");
}
}
The following output is produced:

We are passing a string as a message argument:


System.out.println("This application is running");
The string itself is:
"This application is running"
A string is a sequence of characters treated as a single object. String objects are instance
of the String class.

Applet example using a String object


Just as the simple Java application above displays a String object to the console, we have
also encountered String objects being drawn onto the graphics object of an Applet
window:
// <APPLET code="DrawStringApplet.class" width=275 height=100></APPLET>

import java.applet.Applet;
import java.awt.*;

public class DrawStringApplet extends Applet


{
// methods

public void paint( Graphics g )


{
g.drawString( "This applet is running", 100, 30 );
}
} // class

When compiled and run with the appletviewer:

the screen should look as follows:


In this example the string "This applet is running"is passed as an argument when
the message:

drawString( "This applet is running", 100, 30 );


is send to theGraphicsobject g:
g.drawString( "This applet is running", 100, 30 );

Motivation for String class

As you may have found in the first part of this unit, arrays of characters can be a little
fiddly to deal with, since each character element has to be dealt with individually.

The text "hello" could be seen as a kind of array. It has 5 elements. Element 0 is the
character "h", element 1 is the "e" and so on. This can be written in Java like this:

char text[] = {'h','e','l','l','o'};


After this line, the array "text" will contain the five characters that make up the word "hello".
We can read the individual array elements in just the same way as any other array, e.g.,
char myChar = text[4];
This will make the character variable called "myChar" contain the character "o".

However, this is not a very useful way of manipulating text except when we need to
process individual characters. Normally we would use a String object to work with such
text.

The String class, provided as 'built-in' by the developers of the Java language, makes
working with sequences of characters much easier. The String class defines methods for
many actions, including:

 finding the length of a string


 locating a character or sub-string within a string
 concatenating two strings together to create a new String object
 converting primitive types to Strings
 comparing the values inside String objects
Since many tasks where people interact with computers involves working with text on
screen (word processors, databases, document viewing on the internet etc.) providing a
class to make working with sequences of characters makes a lot of sense.

Strings as objects

An object of class String (note the capital 'S' since this is a class identifier) stores a
sequence of characters. New String objects can be created to have the value of the joining
together of two or more existing strings. New String objects can also be created to have
the value of some modified existing String object. Strings are objects (not primitive data
types) — and so one must think in object terms of Classes, instance objects, methods
and messages

In the same way that numbers like 2 and 3 are assumed to be integers, and numbers like
2.1 and 3.6 are assumed to be floating point numbers (with an integer and a fractional
part), anything in double quotes is assumed by the Java compiler to be a String. So we
can write:

String text = "hello";


or
String text = new String("hello");
Which creates a new String object and sets it equal to the text "hello". This is a slightly
different way of representing text to the character array method described in the previous
section.

We can also concatenate ('add') strings together to form a new String object, so this
line:

String text = new String("hello" + " " + "there");


results in the String object called "text" being set equal to the text "hello there".

Since Strings are objects, normally they are manipulated by means of methods (described
in the next unit). So, for example, this line:

newText = text.substring(1, 3);


will make the String called newText equal to the first, second and third characters from
the String called "text".

There are many other methods that can be carried out on Strings; see Deitel & Deitel and
the Java documentation for full details.

Individual characters in String objects

String objects are not arrays, therefore we cannot use the square bracket notation to refer
to or change a particular character in a String.
However, we can use the String class method charAt() which allows us to find out what
character is at a particular position in a String object.

So although the String class is very versatile, what we cannot do is something like the
following:

String text = "hello";


char x = text[1];
It appears to be a sensible way to assign the character variable x to be equal to the first
character in the String variable text. However, it is not permissible because text is an
object, not an array. We can, however, write
String text = "hello";
char x = text.charAt(1);
which has the effect we wanted to achieve.

Length of String objects

For the same reason, if "text" is a String object, we can't get its length by writing

int lengthOfString = text.length;


but we can write
int lengthOfString = text.length
This will return an integer value, which is the length of the String variable called "text".

The reason for this is that the class String provides a length() method, whereas .length
is how we find out the length of an array.

Such differences between [1] and charAt(1), and length verses length() are things
are often confusing when first encountered. However, as you progress in Java
programming you will come to understand why these seemingly arbitrary distinctions
occur.

Strings — Activities, Exercises and Review Questions

Activity 4 – Counting spaces in a string

Activity 5 – Reversing a string

Computer-based Activities

Activities
Activity 1 – Applet to display and total array elements

(1) Write an applet creates an int array called capacity , which records for 4 machines
how many products they can produce each hour:

 machine 0 produces 55 products per hour


 machine 1 produces 34 products per hour
 machine 2 produces 80 products per hour
 machine 3 produces 101 products per hour

(2) add a loop to your applet, so the contents of the array are displayed in the applets
window.

Write your applet so that the screen is similar to the following:

(3) add a loop to your applet that calculates the total capacity of all 4 machines

Discussion/Suggested solution to Activity 1

Applet to display and total array elements

(1) declare and define the array as follows:

int capacity[] = new int[4];

place the values into the array as follows:

capacity[0] = 55;
capacity[1] = 34;
capacity[2] = 80l
capacity[3] = 101;

The array should have the values as follows after such actions:

capacity[]

element value
capacity[0] 55

capacity[1] 34

capacity[2] 80

capacity[3] 101

You may wish to refer to the full listing of CapacityApplet.java — version 1

(2) Drawing, by convention, takes place in the Paint() method. So we shall be adding
lines to that method.
We need to display several pieces of text onto the applets graphic area, so we shall
introduce 2 variables to store the current X and Y position of text to be drawn:

// local variables for position of text


int x = 10;
int y = 10;

We display the class name in the applets window as usual, this time using variables x
and y (and we add 25 to the Y value, so the next text is displayed lower down the window):

// display class name in window


g.drawString("Capacity Applet - version 2", x, y );
y = y + 25;

A for loop (or we could use a counter controlled while loop) can be used to iterate through
each element of the array. We introduce an integer variable index which will be used to
refer to the index of the current element at any point during the loop.

int index;

The loop needs to start at 0 (since element 0 is the first in an array), and need to go up
to the length of the array (which we can find using the array variable capacity.length ).
Once the value of index reaches capacity.length we should exit the loop (we should not
process the element whose index is capacity.length (i.e. 4) since this would be an array
bounds exception).

for( index = 0; index < capacity.length; index++)


For each element being processed by the loop, we can simply display a string showing
the element location and appending its value. We also need to increase the Y position so
each line of text appears below the previous:

{
g.drawString("capacity[" + index + "] = "
+ capacity[index], x, y );
y = y + 20;
}

You may wish to refer to the full listing of CapacityApplet.java — version 2

(3) To calculate the total is quite straightfoward. We need an integer variable in which to
store the total:

int total = 0;

To keep things neat, we shall do the calculation inside the init() method, and the display
of the total inside the paint() method. Since the variable total will need to be referred to
in both these methods, this variable must be declared as an instance variable (i.e. not
local to just a single method).

We can use a for loop, once again, to iterate through each element. In this case the
action for ach element is to simply add its value to our total variable.

// calculate total
int index;
for( index = 0; index < capacity.length; index++)
total = total + capacity[ index ];

At the end of our paint() method we can add a line to display the total in the window:

// display total
g.drawString("Total of values is: " + total, x, y);

You may wish to refer to the full listing of CapacityApplet.java — version 3

Activity 2 — Display and highest value of a 'float' array

(1) Create an array called sales of the following double variables

10.5
9.01
16.67
11.22
88.33
5.55

(2) Modify your applet to display the values of these variables in the applet's window

(3) Modify your applet to also display the highest value in this array

the screen should look as follows when run:

Discussion/Suggested solution to Activity 2

Display and highest value of a 'float' array

(1) We need to declare and define a double array sales with 6 elements:

double sales[] = new double[6];

We can place the values into the array inside the init() method as follows:

sales[0] = 10.5;
sales[1] = 9.01;
sales[2] = 16.17;
sales[3] = 11.22;
sales[4] = 88.33;
sales[5] = 5.55;

The array should have the values as follows after such actions:

sales[]
element value
sales[0] 10.5

sales[1] 9.01

sales[2] 16.67

sales[3] 11.22

sales[4] 88.33

sales[5] 5.55

In our paint() method we'll add variables for the (X, Y) position of text, and display the
name of this class:

// local variables for position of text


int x = 10;
int y = 10;
// display class name in window
g.drawString("Double Array Applet - version 1", x, y );

You may wish to refer to the full listing of DoubleArrayApplet.java — version 1

(2) Just as for the previous activity, we can introduce a for loop, and an index variable.
For each iteration of the loop we should display the value inside the corresponding array
element, and increase the Y position for the next piece of text to be displayed:

// loop to display each element of 'capacity'


int index;
for( index = 0; index < sales.length; index++)
{
g.drawString("sales[" + index + "] = " + sales[index],
x, y );
y = y + 20;
}

You may wish to refer to the full listing of DoubleArrayApplet.java — version 2

(3) Just as for the previous activity, we can add a new instance variable, we'll call it
maximum this time:

double maximum = 0;

some calculations inside our init() method:

// calculate maximum value in array


// loop to test each element of array
int index;
for( index = 0; index < sales.length; index++)
if( sales[index] > maximum )
maximum = sales[index];
so we test whether each element is greater than the current version of maximum (this is
why maximum was initialised to zero). If the current element is greater than maximum,
then we assign the value of this element to the maximum variable.

We also need to add a statement to display this maximum value inside our paint()
method.

// display maximum value


g.drawString("maximum value in array = " + maximum, x, y );

You may wish to refer to the full listing of DoubleArrayApplet.java — version 3

Activity 3 – Reversing a 'char' array

(1) Write an applet that displays a char array called forward containing the letters:

'h' 'e' 'l' 'l' 'o'

The screen should look as follows when the appletviewer is executed:

(2) Modify your applet so that a second char array, called backward, is created, that
processes the elements of array forward, and places the reverse values into array
backward.

You should write this code to be general enough so that if the length or values inside
forward are changed, your loop to put values into backward does not need to be changed.
The screen should look as follows when executed:

(3) Test how general your code is, by changing the characters that forward is initialised
to.

For example, try it with the initialisation:

char forward[] =
{ 'I', 'N', 'T', '4', '1', '2', '0', ' ', 'J', 'a', 'v', 'a' };

When executed your screen should appear as follows:

Discussion/Suggested solution to Activity 3


Reversing a 'char' array

(1) We need to declare and define a char array forward with 5 elements:

char forward[] = new char[5];

We can place the values into the array inside the init() method as follows:

forward[0] = 'h';
forward[1] = 'e';
forward[2] = 'l';
forward[3] = 'l';
forward[4] = 'o';

In fact, we can combine the declaration, definition and initialization of array forward as
follows:

char forward[] = {'h', 'e', 'l', 'l', 'o'};

The Java compiler will count how many characappear between the braces to determine
the size of the array.

Whichever way we set up our array, it should have the values as follows after such
actions:

forward[]

element value
forward[0] 'h'

forward[1] 'e'

forward[2] 'l'

forward[3] 'l'

forward[4] 'o'

To display these letters, rather than looping and displaying each character one by one,
we can use the Graphics method drawChars() as follows:

// Display string "char array 'forward' contains:" in window


g.drawString("char array 'forward' contains:", x, y );
y = y + 20;
// use Graphics method 'drawChars' to display char array
g.drawChars( forward, 0, forward.length, x + 10, y );

Note, when we display the char array, we indent it slightly on screen by displaying at (x +
10, y) rather than just (x, y).
You may wish to refer to the full listing of ReverseArrayApplet.java — version 1

(2) To create an array backward, which contains the characters of array forward in reverse
order, we must first declare and define an array backward to be the same length as array
forward.

So we declare a new instance variable backward:

char backward[];

and define this to be an array of size forward.length in our init() method:

backward = new char[ forward.length ];

Now, we need to add some more code in out init() method, to loop through the elements
of array forward, and place them in their appropriate locations in array backward.

What we wish to achieve, for example when array forward contains 'h', 'e', 'l', 'l', 'o', is
the following:

forward[] backward[]

element value element value

forward[0] 'h' backward[0] 'o'

forward[1] 'e' backward[1] 'l'

forward[2] 'l' backward[2] 'l'

forward[3] 'l' backward[3] 'e'

forward[4] 'o' backward[4] 'h'

As a general rule, the character to be placed in backward[ index ] is the character


forward[ forward.length - index - 1].

So

backward[ 0 ] = forward[ 5 - 0 - 1 ] = forward[ 4 ] = 'o'


backward[ 1 ] = forward[ 5 - 1 - 1 ] = forward[ 3 ] = 'l'
backward[ 2 ] = forward[ 5 - 2 - 1 ] = forward[ 2 ] = 'l'
backward[ 3 ] = forward[ 5 - 3 - 1 ] = forward[ 1 ] = 'e'
backward[ 4 ] = forward[ 5 - 4 - 1 ] = forward[ 0 ] = 'h'

Thus, the loop we need to write in method init() to create our backward array is:

// loop to put chars from 'forward' into 'backward'


// (in reverse order)
int index;
for( index = 0; index < forward.length; index++)
backward[ index ]=forward[ forward.length - index - 1 ];

To display the char array backward, we can use the Graphics method drawChars again:

y = y + 30;
// Display "char array 'backward' contains:" in window
g.drawString("char array 'backward' contains:", x, y );
y = y + 20;
// use Graphics method 'drawChars' to display char array
g.drawChars( backward, 0, backward.length, x + 10, y );

You may wish to refer to the full listing of ReverseArrayApplet.java — version 2

(3) Apart from the changed line initialising array forward, no other changes should be
necessary !

Activity 4 – Counting spaces in a string

Write a Java applet that counts the number of spaces in the string of text "the cat sat on
the mat". It should do this by using a String variable and a loop.

The screen should looks as follows when run:


Discussion/Suggested solution to Activity 4

Counting spaces in a string

First we need to declare and initialise out String object (we'll call it text):

String text = "The cat sat on the mat";

we will also need an int variable to count the integer number of spaces. This we shall
call numberOfSpaces and we will initialise it to zero (since at this point no spaces have
been counted):

int numberOfSpaces = 0;

We will need loop through each position of the String text. For this we can use a for
loop, and a counter (which will refer to the position of the character in the String being
looked at for the current loop iteration). A Java programming convention is to call the int
counter i if the code is so simple it should be obvious what i is in the loop statements
(short variables names make code shorter, but must be weighed with writing code that is
hard to understand).

Our loop counter i should start at 0 (the position of the first character in the String object),
and should end at text.length(). We must write our code so the loop terminates when I
reaches XX, there is no character in the String at position text.length() — the characters
are from 0 .. text.length() - 1 :

for (int i = 0; i < text.length(); i++)

For each iteration of our loop, we need to test (we'll use an if statement) whether the
current character in the String object is a space or not. If the character is a space, then
we should add 1 to our numberOfSpaces variable.

if (text.charAt(i) == ' ')

numberOfSpaces++;

One the loop has terminated, we can draw a message in the applet's window, stating how
many spaces were found:

g.drawString ("There are " + numberOfSpaces + " spaces", 20, 40);

You may wish to view the complete listing for this solution: CountSpaces1.java.

Activity 5 – Reversing a string


Write a Java applet that reverses the letters of a string of text.

For example, given the name "Mary Smith" it should display "htimS yraM".

Use only String objects (i.e. not arrays of characters) in your applet.

The screen should look something similar to the following when executed:

Discussion/Suggested solution to Activity 5

Reversing a string

We need to work with (at least) two String objects, let's call them forwards and backwards.
We can initialize the forward String object with the text to be reversed, for example
"hello":

String forwards = new String("hello");

String backwards = "";

The solution we shall adopt is to create a loop, that will retrieve the characters from the
forwards String in reverse order. The location of the last character in String forwards is
forwards.length() - 1, since the first character is at position 0. We shall create an int
variable called lastCharPos to store this value, to make our loop easier to read:

int lastCharPos = (forwards.length() - 1);

In our loop, we shall use an int variable i to refer to the position of the character we are
currently working with, so our loop starts as follows:
int i;

for( i = lastCharPos; i >= 0; i-- )

Notice the use of the decrement operator --, this means that after each execution of the
loop the value of variable i is reduced by 1. Also note that the loop will continue while i
>= 0 — the loop will terminate as soon as i becomes less than zero.

All that remains is the action to perform within the loop. We wish to retrieve a character
at a time from the forwards String, and append (stick it on the end) of the a new String
we are creating for variable backwards. Strings cannot be changed once created — they
are immutable. However, a String variable, such as backwards can be made to refer to a
different object. For each iteration of the loop we shall create a new String object, formed
by appending (also called concatenating) the existing String referred to by the backwards
variable, with the current character in the forwards String:

backwards = new String( backwards + forwards.charAt( i ) );

You may wish to view the full solution listing: StringReverse.java

NOTE:

There is, in fact, a more concise way to write the loop statement that concatenates
backwards with the character from forwards:

backwards = backwards + forwards.charAt( i ) ;

since the + is actually a String operator that will automatically create a new String object
as the evaulation of the expression.

In fact, we could make this expression even shorted, by using the += concatenation
operator:

backwards += forwards.charAt( i ) ;

You may wish to try out these changes yourself.

Exercises

Exercise 1 — Declaring and Defining arrays

(1) Declare an array of char called surName

(2) Declare an array of int called ages

(3) Declare an array of Object called things


(4) Define array surName to have a size of 20 chars

(5) Define array ages to have a size of 5 ints

(6) Define array things to have a size of 1000 Objects

(7) In a single line, declare an array of char address with a size of 55

Discussion/Suggested solution to Exercise 1

Declaring and Defining arrays

(1) The following line of code will declare a variable with the identifier (variable name) of
surName, that is able to refer to an array of char variables:

char surName[];

(2) To declare our ages array, able to refer to an array of int variables:

int ages[];

(3) To declare our things array, able to refer to an array of Object variables:

Object thingsp[];

(4) The following will now define array surName to have a size of 20 char variables:

surName = new char[20];

(5) The following will now define array ages to have a size of 5 int variables:

ages = new int[5];

(6) The following will now define array things to have a size of 1000 Object variables:

things = new Object[1000];

(7) We can combine the statements for declaring an identifier that can refer to an array of
a certain type of variables, and the definition of how many of that type of variables the
array is to store. The following line declares an array address to be able to store 55 char
variables:

char address = new char[55];


Exercise 2 — Why only run-time array bounds exception errors?

What is it about the way the compiler works than means that it can't detect array bounds
exception errors?

Discussion of Exercise 2

The compiler only checks the syntax of the program, not its logic. The Java syntax rules
simply say that the array index must be an integer. That the integer must be greater than
or equal to zero is not an issue of syntax, but of logic. The compiler is not designed to
detect logical errors. If the computer could do this, we wouldn't need programmers!

Exercise 3 – Arrays Summary

Complete the following statements that summarize the concepts explored in the 'Arrays'
section of this unit:

Arrays are used to represent a sequence of _________ (possibly a large number) all of
the same type, when we don't want to assign an identifier to each variable.

Instead of an individual identifier, each variable is identified by a combination of the


array __________ and a number representing the array _____.

Individual variables within an array are called ________.

Arrays are very often used in conjunction with _____, so that some action can be
performed upon every variable in the array.

Discussion of Exercise 3

Arrays Summary

Suggested completed summary statements are as follows:

Arrays are used to represent a sequence of variables (possibly a large


number) all of the same type, when we don't want to assign an identifier to
each variable.

Instead of an individual identifier, each variable is identified by a


combination of the array identifier and a number representing the array
index.
Individual variables within an array are called elements.

Arrays are very often used in conjunction with loops, so that some action
can be performed upon every variable in the array.

Exercise 4 – Array Exercises

Complete exercises 7.8, 7.12 from Chapter 7 of Deitel and Deitel pp 305-306.

Exercise 5 – Strings Summary

Complete the following statements that summarise the concepts explored in the 'Arrays'
section of this unit:

An object of class String stores a ________ of characters.

Strings are _______ (not _________ data types) — and so one must think in object
terms of _______, instances, _______ and messages

New String objects can be created to have the value of the _____________ (joining
together) of two or more existing strings.

Discussion of Exercise 5

Strings Summary

Suggested completed summary statements are as follows:

An object of class String stores a sequence of characters.

Strings are objects (not primitive data types) — and so one must think in
object terms of Classes, instances, methods and messages

New String objects can be created to have the value of the concatenating
(joining together) of two or more existing strings.

Exercise 6 – Comparing arrays and strings


Produce a table summarising the differences between manipulating text using character
arrays and String objects. You will almost certainly have to refer to the textbook to do this
fully

Comparing arrays and strings

character array instance of String


Can read each character individually
Can read each character
using charAt() method, but can't
individually using [] notation
write
Can write each character cannot write each character
individually using [] notation individually
Can't change size after
Can't change size after creation
creation

Is not an object Is an object of class String

Can't concatenate Can concatenate, using +

Can be initialized like any other Can be initialized from a string


array, e.g., {'x','y','z'} constant, e.g., "xyz"

Arrays

Review Question 1

What is an 'array bounds exception'? What array indexes will always produce and array
bounds exception, however large the array is?

Discussion of Review Question 1

Discussion of Review Question 1

An array bounds exception is the error generated when a program tries to read or write
an element of an array and the index is beyond the size of the array. Any negative number
used as an array index will produce an array bounds exception. For example:

x[-1] = 0;
will always produce an array bounds exception, however large the array `x' is.

Likewise, an index of <array>.length or greater will also always created an array bounds
exception.

Review Question 2

Suppose I am writing a program concerned with weather forecasting. I declare an array


of doubles to store the temperature measured every day, like this:

double dailyTemperature[] = new int[365];

Assuming I have a way of storing the daily temperatures in the array, how could I work
out the average annual temperature? Write a few lines of Java to do this (not a whole
program).

Discussion of Review Question 2

Discussion of Review Question 2

There are many ways to do this; one possibility is:

double total = 0;
for (int i = 0; i < 365; i++)
total = total + dailyTemperature[i];
double average = total / 365;

Strings

Review Question 3

What exactly is the output from this section of program:

string s1 = "Java";
string s2 = "is";
string s3 = "easy";
System.out.println( s1 + s2 + s3 );

Discussion of Review Question 3

Discussion of Review Question 3


The text:

Javaiseasy

Many students assume that when words are concatenated (joined) together, spaces are
inserted automatically. However, this is not true. If you want spaces you have to put them
in yourself, for example:

System.out.println( s1 + " " + s2 + " " + s3 );

Review Question 4

Why is this section of Java rejected by the compiler?

String s = "abc";
System.out.println(s[1]);

Modify it so that it works — that is, it prints the letter `b'.

Discussion of Review Question 4

Discussion of Review Question 4

The error is due the fact that s is a String object, not an array. We can't use the square
bracket notation on objects.

To access the first character of String s we need the charAt() method instead.

String s = "abc";
System.out.println(s.charAt(1));

Review Question 5

If two Strings contain the same text, then we would expect them to be equal in some
sense. For example, consider this section of Java:

String string1 = "hello";


String string2 = "hello";
String string3 = "there";
if (string1 == string2)
System.out.println("strings 1 and 2 are equal");
if (string1 == string3)
System.out.println("strings 1 and 3 are equal");
We might expect this section of program to print:

Strings 1 and 2 are equal

Because both contain the word "hello". In fact, neither line is printed; Java does not think
the "hello" is equal to "hello"! This may seem rather odd at first. If x and y were integers,
and both had the value 2 , thJava would think x and y were equal. So why does Java
treat Strings and integers differently in this respect?

(Hint: what is different in the way these data types are implemented).

There is a short answer to this question, and a longer one which takes into account the
philosophy behind the answer (i.e. why Java works this way).

If we can't use == to test whether two strings have the same text, how can we do it?

Discussion of Review Question 5

Discussion of Review Question 5

Integers are primitive data types. There is only one way that integers can be equal: they
have the same number. Strings, however, are objects.

When are two objects equal? This is a rather difficult point. Here is an example. Kevin
owns a lap-top computer, a Dell Inspiron 3000. The Dell corporation has made many
thousands of these computers; perhaps you own one as well. If you do, is your Dell
Inspiron 3000 equal to Kevin's Dell Inspiron 3000? It may be identical in every respect,
but it is not the same machine. This is the key concept. In Java, for two things to be equal,
they must refer to the same thing, rather than referring to things that have the same value.

Another example could be that there are 2 copies of the same book in a library. These
two objects are not the same object, so Fred could borrow copy 1 and Yolanda could
borrow copy 2. Most likely a librarian will number the copies so that each can be referred
to individually. It is the same with Java, each object has a unique reference (i.e. its location
in memory). Two objects might have the same values, but if they are stored at different
locations in memory then Java will not consider them to be the same object. However,
two variables could both refer to the same object (i.e. the same location in memory), in
which case these two variables would both be referring to the same object, and Java
would consider them to be equal.

Just because string1 and string2 contain the same text, this does not make them the
same string, anymore than your computer is the same computer as Kevin's computer just
because it is the same model.

To test whether two strings have the same text values, we can write:
If( string1.equals(string2) )
{
System.out.println("strings 1 and 2 are equal");
}

Discussion Topics

There are many new concepts in this unit. If you want to discuss with your colleagues or
make comments about the concepts to them, use the on-line facilities.

Discussion Topic 1

Contribution for Discussion Topic 1 – Why different mechanisms for handling


text?

Arrays provide an effective way to process text character by character. Strings provide
an effective way to process text as units — for example 5 lines of text could be stored in
5 Strings, or in fact all in a single String.

The developers of Java recognised that for different software systems text needs to be
dealt with in both ways. They therefore provided the array type and the String class, and
appropriate operators and methods to make the writing of programs to handle text
straightforard.

Discussion Topic 2 — Why use the UNICODE rather than ASCII character set?

Computers only `understand' numbers. If we want to manipulate letters and symbols, we


must allocate a number to each different letter and symbol. It doesn't matters what
number we give to any symbol, as long as everyone does the same.

Most computer programming languages use something called the ASCII coding scheme
to do this. In this scheme, for example, the letter `A' is number 65, `B' is 66 and so on.
This scheme has a maximum of 256 symbols (because this is the largest number that
can be stored in one byte). Java, on the other hand, uses the UNICODE coding scheme,
where each symbol has a number between 0 and 65535 (two bytes). This means that a
text string in Java requires twice as much memory as it would in most other languages.

Why did the Java developers make this decision? What are the advantages and
disadvantages?
Contribution for Discussion Topic 2

Why use the UNICODE rather than ASCII character set?

UNICODE is an internationally recognised standard character set. Once again the


developers of Java were motivated in a choice by a desire for portability.

By choosing an international standard the Java character set is both well defined and
understood. Also UNICODE requires two bytes because of the very large range of
international characters and symbols it provides — UNICODE supports many different
alphabets, well beyond the European symbols supported by ASCII.

Reflection on Learning Experience

In your Learning Journal write up your experience of your learning on this unit. Say what
you thought was good or bad, what you had difficulty understanding, and how you
resolved your problems.

Code listings

Listing of CountSpace.java (See the comment for the program it's for reverses
a text
string )
// CountSpace1.java
// A program that reverses a text string.
// Note that there are many ways to do this; this program only
demonstrates one way
// Kevin Boone, August 1999
import java.applet.Applet;
import java.awt.*;
public class Reverse1 extends Applet
{
public void paint (Graphics g)
{
// 'text' is the String to be reversed
String text = "Fred Bloggs";
// Start by creating a character array of exactly the same
// length as `text'.
// This is because Java allows individual elements of an array
// to be changed,
// but not individual characters of a String
char reversedText[] = new char[text.length()];
// Now move each character in `text' to the right place in
// `reversedText'
for (int i = 0; i < text.length(); i++)
reversedText[i] = text.charAt(text.length() - i - 1);
// `reversedText' is an array; Java will not allow us to use
//`drawString' to
// print an array (it can only print Strings). So we create a new
//String
// that has exactly the same text as `reversedtext'
String reversedTextString = new String(reversedText);
// Now print the String
g.drawString (reversedTextString, 20, 40);
}
}

Listing of CapacityApplet.java — version 1

// <APPLET code="CapacityApplet.class" width=275 height=200></APPLET>


// CapacityApplet - version 1
import java.applet.Applet;
import java.awt.*;
public class CapacityApplet extends Applet
{
// instance variables
int capacity[] = new int[4];
// methods
public void init()
{ capacity[0] = 55;
capacity[1] = 34;
capacity[2] = 80;
capacity[3] = 101;
}
public void paint( Graphics g )
{
g.drawString("CapacityApplet", 10,10 );
}
} // class

Listing of CapacityApplet.java — version 2

/ / <APPLET code="CapacityApplet.class" width=275 height=200></APPLET>


// CapacityApplet - version 2
import java.applet.Applet;
import java.awt.*;
public class CapacityApplet extends Applet
{
// instance variables
int capacity[] = new int[4];
// methods
public void init()
{
capacity[0] = 55; capacity[1] = 34;
capacity[2] = 80;
capacity[3] = 101;
}
public void paint( Graphics g )
{
// local variables for position of text
int x = 10;
int y = 10;
// display class name in window
g.drawString("Capacity Applet - version 2", x, y );
y = y + 25;
// loop to display each element of 'capacity'
int index;
for( index = 0; index < capacity.length; index++)
{
g.drawString("capacity[" + index + "] = " + capacity[index],x,y);
y = y + 20;
}
}
} // class

Listing of CapacityApplet.java — version 3

// <APPLET code="CapacityApplet .class" width=275 height=200></APPLET>


// CapacityApplet - version 3
import java.applet.Applet;
import java.awt.*;
public class CapacityApplet extends Applet
{
// instance variables
int capacity[] = new int[4];
// has to be an instance variable, since referred to in "init()"
//and "paint()"
// so cannot be local to either method
int total = 0;
// methods
public void init()
{
capacity[0] = 55;
capacity[1] = 34;
capacity[2] = 80;
capacity[3] = 101;
// calculate total
int index; for( index = 0; index < capacity.length; index++)
total = total + capacity[ index ];
}
public void paint( Graphics g )
{
// local variables for position of text
int x = 10;
int y = 10;
// display class name in window
g.drawString("Capacity Applet - version 3", x, y );
y = y + 25;
// loop to display each element of 'capacity'
int index;
for( index = 0; index < capacity.length; index++)
{
g.drawString("capacity[" + index + "] = " + capacity[index], x,
y );
y = y + 20;
}
// display total
g.drawString("Total of values is: " + total, x, y);
}
} // class

Listing of DoubleArrayApplet.java — version 1

// <APPLET code="DoubleArrayApplet.class" width=275


height=200></APPLET>
// DoubleArrayApplet - version 1
import java.applet.Applet;
import java.awt.*;
public class DoubleArrayApplet extends Applet
{
// instance variables
double sales[] = new double[6];
// methods
public void init()
{
sales[0] = 10.5;
sales[1] = 9.01;
sales[2] = 16.17;
sales[3] = 11.22;
sales[4] = 88.33;
sales[5] = 5.55;
}
public void paint( Graphics g )
{
// local variables for position of text
int x = 10;
int y = 10;
// display class name in window
g.drawString("Double Array Applet - version 1", x, y );
}
} // class

Listing of DoubleArrayApplet.java — version 2

// <APPLET code="DoubleArrayApplet.class" width=275


height=200></APPLET>
// DoubleArrayApplet - version 2
import java.applet.Applet;
import java.awt.*;
public class DoubleArrayApplet extends Applet
{
// instance variables
double sales[] = new double[6];
// methods
public void init()
{
sales[0] = 10.5;
sales[1] = 9.01;
sales[2] = 16.17;
sales[3] = 11.22;
sales[4] = 88.33;
sales[5] = 5.55;
}
public void paint( Graphics g )
{
// local variables for position of text
int x = 10;
int y = 10;
// display class name in window
g.drawString("Double Array Applet - version 2", x, y );
y = y + 20;
// loop to display each element of array
int index;
for( index = 0; index < sales.length; index++)
{
g.drawString("sales[" + index + "] = " + sales[index], x, y );
y = y + 20;
}

}
} // class

Listing of DoubleArrayApplet.java — version 3

// <APPLET code="DoubleArrayApplet.class" width=275


height=200></APPLET>
// DoubleArrayApplet - version 3
import java.applet.Applet;
import java.awt.*;
public class DoubleArrayApplet extends Applet
{
// instance variables
double sales[] = new double[6];
double maximum = 0;
// methods
public void init()
{
sales[0] = 10.5;
sales[1] = 9.01;
sales[2] = 16.17;
sales[3] = 11.22;
sales[4] = 88.33;
sales[5] = 5.55;
// calculate maximum value in array
// loop to test each element of array
int index;
for( index = 0; index < sales.length; index++)
if( sales[index] > maximum )
maximum = sales[index];
}
public void paint( Graphics g )
{
// local variables for position of text
int x = 10;
int y = 10;
// display class name in window
g.drawString("Double Array Applet - version 3", x, y );
y = y + 20;
// loop to display each element of array
int index;
for( index = 0; index < sales.length; index++)
{
g.drawString("sales[" + index + "] = " + sales[index], x, y );
y = y + 20;
}
// display maximum value
g.drawString("maximum value in array = " + maximum, x, y );
}
} // class

Listing of ReverseArrayApplet.java — version 1

// <APPLET code="ReverseArrayApplet.class" width=275


height=200></APPLET>
// ReverseArrayApplet - version 1
import java.applet.Applet;
import java.awt.*;
public class ReverseArrayApplet extends Applet
{
// instance variables
char forward[] = {'h', 'e', 'l', 'l', 'o'};

// methods
public void init()
{
// nothing needed here for version 1 !
}
public void paint( Graphics g )
{
// local variables for position of text
int x = 10;
int y = 10;
// display class name in window
g.drawString("Reverse Array Applet - version 1", x, y );
y = y + 20;
// Display "char array 'forward' contains:" in window
g.drawString("char array 'forward' contains:", x, y );
y = y + 20;
// use Graphics method 'drawChars' to display char array
g.drawChars( forward, 0, forward.length, x + 10, y );
}
} // class

Listing of ReverseArrayApplet.java — version 2

// <APPLET code="ReverseArrayApplet.class" width=275


height=200></APPLET>
// ReverseArrayApplet - version 2
import java.applet.Applet;
import java.awt.*;
public class Rextends Applet
{
// instance variables
char forward[] = {'h', 'e', 'l', 'l', 'o'};
char backward[];
// methods
public void init()
{
// define array backward
backward = new char[ forward.length ];
// loop to put chars from 'forward' into 'backward'
// (in reverse order)
int index;
for( index = 0; index < forward.length; index++)
backward[ index ] = forward[ forward.length - index - 1 ];
}
public void paint( Graphics g )
{
// local variables for position of text
int x = 10;
int y = 10;
// display class name in window
g.drawString("Reverse Array Applet - version 2", x, y );
y = y + 20;
// Display "char array 'forward' contains:" in window
g.drawString("char array 'forward' contains:", x, y );
y = y + 20;
// use Graphics method 'drawChars' to display char array
g.drawChars( forward, 0, forward.length, x + 10, y );
y = y + 30;
// Display "char array 'backward' contains:" in window
g.drawString("char array 'backward' contains:", x, y );
y = y + 20;
// use Graphics method 'drawChars' to display char array
g.drawChars( backward, 0, backward.length, x + 10, y );
}
} // class

Listing of CountSpace1.java
/ / CountSpace1.java
// A program that counts the spaces in a text string
// Kevin Boone, August 1999
// modified Matt Smith, Sep 1999
// <APPLET code="CountSpace1.class" width=275 height=200></APPLET>
import java.applet.Applet;
import java.awt.*;
public class CountSpace1 extends Applet
{
public void paint (Graphics g)
{
int numberOfSpaces = 0;
String text = "The cat sat on the mat";
g.drawString ("Counting spaces in '" + text + "'", 20, 20);

for (int i = 0; i < text.length(); i++)


if (text.charAt(i) == ' ')
numberOfSpaces++;
g.drawString ("There are " + Integer.toString(numberOfSpaces) +
"spaces", 20, 40);
}
}

Listing of StringReverse.java

// StringReverse.java
// Create a String object whose characters are the reverse of another String
object
// <APPLET code="StringReverse.class" width=275 height=200></APPLET>
import java.applet.Applet;
import java.awt.*;

public class StringReverse extends Applet


{
// instance variables
String forwards = new String("hello");
String backwards = "";
public void paint (Graphics g)
{
g.drawString( "forwards: " + forwards, 20, 20 );
int lastCharPos = (forwards.length() - 1);
int i;
for( i = lastCharPos; i >= 0; i-- )
backwards = new String( backwards + forwards.charAt( i ) );
g.drawString( "backwards: " + backwards, 20, 40 );
}
}
Additional Activit y 1

(Airline Reservations System) A small airline has just purchased a computer for its new
automated reservations system. You have been asked to program the new system. You
are to write a program to assign seats on each flight of the airline’s only plane (capacity
10 seats).

Your program should display the following menu of alternatives:


Please type 1 for “smoking”
Please type 2 for “non-smoking”

If the person types 1, your program should assign a set in the smoking section (seats 1-
5). If the person types 2, you program should assign a seat in the non-smoking section
(seats 6-10). Your program should then print a boarding pass indicating the person’s
seat number and whether it is in the smoking or non-smoking section of the plane.

Use a single dimensional array to represent the seating chart of the plane. Initialise all
the elements of the array to 0 to indicate that the seats are empty. As each seat is
assigned, set the corresponding elements of the array to 1 to indicate that the seat is no
longer available. Your program, should of course, never assign a seat that has already
been assigned. When the smoking section is full, your program should ask the person if
it is acceptable to be placed in the non-smoking section (and vice versa). If yes, make
the appropriate seat assignment. If no, print the message “Next flight leaves in 3 hours”.
(This is Exercise 7.18 p 308 , Chapter 7 of Deitel and Deitel)

Additional Activit y 2

Complete exercise 10.9 p 506 Chapter 10 of Deitel and Deitel

Das könnte Ihnen auch gefallen