Tom Kelliher, CS 116
Dec. 9, 2002
Lab and postlab 7 due today.
Extra credit applet due Wednesday.
Final Friday in HS 153 3:00 to 5:00.
This example pulls together a lot of what we've done this semester.
import java.applet.*;
public class Driver extends Applet
{
Stack s;
public void init()
{
int tempI;
boolean tempB;
s = new Stack(10);
tempB = s.empty(); // Returns true.
s.push(12);
tempB = s.empty(); // Returns false.
s.push(9);
tempI = s.pop(); // Returns 9.
tempI = s.pop(); // Returns 12.
tempB = s.empty(); // Returns true.
}
}
class Stack
{
int topIndex;
int data[];
public Stack(int length)
{
topIndex = -1;
data = new int[length];
}
boolean empty()
{
if (topIndex == -1)
return true;
else
return false;
}
boolean full()
{
if (topIndex == data.length - 1)
return true;
else
return false;
}
int pop()
{
if (empty())
{
// Throw an exception and return.
return 0;
}
else
{
topIndex--;
return data[topIndex + 1];
}
}
void push(int newTop)
{
if (full())
{
// Throw an exception and return.
}
else
{
topIndex++;
data[topIndex] = newTop;
}
}
}
When to use?
Index variable.
Purpose of the break within a switch case.
Remember the precedence table.
Creating your own.
double average(int data[])
{
double average; // dohhh....
The use of the constructor.