Programming and Problem Solving with Java

(やまだぃちぅ) #1

630


d.Write a code segment to calculate the sum of the sales for January.
e.Write a code segment to calculate the sum of the sales for store 2.
f. Write a code segment to calculate the sum of the sales for department 33.
5.In an application you are writing, a doublevariable betapotentially contains a
very large number. Before multiplying betaby 100.0, you want the code to test
whether it is safe to do so. Write an ifstatement that tests for a possible
overflow beforemultiplying by 100.0. Specifically, if the multiplication would
lead to overflow, print a message and don’t perform the multiplication; other-
wise, go ahead with the multiplication.
6.The Vectorclass in java.utilprovides functionality very similar to that offered
by an array. In fact, the underlying data structure isan array. The advantage of a
Vectoris that it can grow and shrink; the disadvantage is that this capability is
time-consuming. To grow beyond the initial size requires the system to create a
larger array and move the objects into it. Listed below are some of the useful
methods in the Vectorclass and the corresponding array operations.

Method Array Equivalent/Explanation
Vector myVector; Object[] myVector;
myVector = newVector( 10 ); myVector = newObject[ 10 ];
myVector.setElementAt(item, 9 ); myVector[ 9 ] = item;
item = myVector.elementAt( 5 ); item = myVector[ 5 ];
myVector.addElement(item); myVector[numItems] = item;
numItems++;
myVector.size() Returns the number of items in myVector
myVector.capacity() myVector.length
a.Run an experiment to determine how many slots are added to aVector
object when you add one more item than you originally stated should be in
the vector.
b.Make a table like the one shown in this exercise showing five other useful
methods in the class.

Programming Problems


1.Write an application that plays Tic-Tac-Toe. Represent the board as a 3  3
character array. The array is initialized to blanks, and each player is asked in
turn to input a position. The first player’s position is marked on the board with
an O, and the second player’s position is marked with an X. Continue the
process until a player wins or the game is a draw. To win, a player must have
three marks in a row, in a column, or on a diagonal. A draw occurs when the
board is full and no one has won.

T


E


A


M


F


L


Y


Team-Fly®

Free download pdf