how to switch if and else statements to try and catch
so i made this program but I have to change the if and else statements to try and catch. any help will be greatly appreciated :) here is the code:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.util.*;
public class ShowIndex extends 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 void init()
{ int i;
for(i=0;i<100;i++)
number[i]=r.nextInt(1000)+1; // random number between 1 and 1000
add(indexlabel);
add(index开发者_如何学JAVAfield);
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]+"");
}
}
Don't use exception handling as flow-control mechanism. Retain the if-clause.
Java has a great tutorial set.
I suggest going through the Exceptions section: (covering try/catch): http://download.oracle.com/javase/tutorial/essential/exceptions/
Try this:
try{
valueField.setText(number[num]+"");
}catch(ArrayIndexOutOfBoundsException e){
valueField.setText("Out of bound");
}
One way is to rewrite your actionPerformed
function:
public void actionPerformed(ActionEvent e) {
String inputString;
int num;
inputString=indexfield.getText();
num=Integer.parseInt(inputString);
try {
valuefield.setText(number[num]+"");
}
catch (Exception e) {
valuefield.setText("Outof Bound");
}
// old version
/*
if(num>99 ||num<0)
valuefield.setText("Outof Bound");
else
valuefield.setText(number[num]+"");
*/
}
I won't explain to you how this code works. It probably won't even compile, I haven't tried. Do a little research. Look at the ideas and try to see how they fit together. Research about array bounds, in array and List format. And the line
catch (Exception e) {
is a bit generic, I'm sure you can improve it.
Are you saying "I have to" because the teacher/boss told you to, or because you assume you have to? What's driving this change? A little thought about what the basic objective might reveal there's no need for a change after all.
精彩评论