import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class ArrayBounds extends Applet implements ActionListener
{
private double[] price;
private String[] product;
private TextField T1,T2,T3,errMess;
private Label L1, L2, L3, L4;
private Panel P1,P2;
private int choice;
public ArrayBounds() //constructor
{
price = new double[6]; // parallel arrays - ie same index used for both
product = new String[6]; // so if we get product 5 we also get price 5
setProducts(); // user-defined methods to fill arrays with data
setPrices();
T1 = new TextField(1);
T2 = new TextField(10);
T3 = new TextField(10);
L1 = new Label("Enter choice 1-6");
L2 = new Label("Product");
L3 = new Label ("Price");
errMess = new TextField(20);
T1.addActionListener(this);
T2.addActionListener(this);
T3.addActionListener(this);
P1 = new Panel();
P2 = new Panel(); // for output error message
P1.add(L1);
P1.add(T1);
P1.add(L2);
P1.add(T2);
P1.add(L3);
P1.add(T3);
add(P1);
}
public void actionPerformed (ActionEvent ae)
{
try
{
P2.setVisible(false);
choice = Integer.parseInt(T1.getText()); // converts text to int
choice--; // subtracts 1 because array starts at zero
T2.setText(product[choice]);
T3.setText(Double.toString(price[choice]));
}
catch (NumberFormatException nf)
{
P2.add(errMess);
errMess.setText("Invalid choice - type a number");
add(P2);
P2.setVisible(true);
validate();
} // end catch
catch (ArrayIndexOutOfBoundsException e)
{
P2.add(errMess);
errMess.setText("No such product");
add(P2);
P2.setVisible(true);
validate();
} // end catch
}
public void setProducts() // method definitions
{
product[0] = "Eggs ";
product[1] = "Bacon ";
product[2] = "Tomatoes ";
product[3] = "Sausages ";
product[4] = "Black Pudding ";
product[5] = "Bread ";
}
public void setPrices()
{
price[0] = 0.85;
price[1] = 1.87;
price[2] = 0.66;
price[3] = 1.25;
price[4] = 1.33;
price[5] = 0.65;
}
} |