Exceptions (array index out bounds exception)
can someone please help me with this. i have to:
- Create an array with 100 randomly chosen integers.
- Create a text field to enter an array index and another textfield to display the array element at the specified index.
- Create a Show Element button to cause thearray element to be displayed. If the specified index is out ofbounds, display the message Out of Bound in the designated area.
this is what i have so far, can someone please tell be what else i have to add.
any help will be greatly appreciated :)
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.util.*;
public class showindexextends Applet implements ActionListener
{ int [] number =new int[100];
Random r= new Random();
Label indexlabel = new Label(" index:");
TextField indexfield = new TextField(10);
Label valuelabel = new Label("value:");
TextField valuefield = new TextField(10);
Button showButton = new Button ("Show Element");
public vo开发者_C百科id init()
{ int i;
for(i=0;i<100;i++)
number[i]=r.nextInt(1000)+1; // random number between 1 and 1000
add(indexlabel);
add(indexfield);
add(valuelabel);
add(valuefield);
add(showButton);
showButton.addActionListener(this);
valuefield.setEditable(false);
}
public void actionPerformed(ActionEvent e)
{ String inputString;
int num;
inputString=indexfield.getText();
num=Integer.parseInt(inputString);
if(num>99 ||num<0)
valuefield.setText("Outof Bound");
else
valuefield.setText(number[num]+"");
}
}
The class declaration is incorrect:
public class showindexextends Applet implements ActionListener
should probably be :
public class showindexextends extends Applet implements ActionListener
You should practice reading the error messages from the compiler and use the clues it gives you to track down the error in your program. It also helps to write your code in an IDE with syntax highlighting. Check out Eclipse.
精彩评论