| Author |
Linear Searches
|
Marie Jeanne Thibault
Greenhorn
Joined: Nov 15, 2003
Posts: 15
|
|
Hi Everyone, I'm having trouble with the last part of my code. No matter what input I enter, the "out of bounds" message is displayed. I'm thinking it's something in the actionPerformed class. I've agonized over this one for about a week now. Thanks, Marie import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ArrayDemo extends JFrame implements ActionListener { //Declare two textfields private JTextField jtfIndex = new JTextField(8); private JTextField jtfElement = new JTextField(8); private JButton jbtShow = new JButton("Show Element");//Declare "Show Element" button //Constructor public ArrayDemo() { setTitle("Show Bounds Error"); //Create panel for the textfields JPanel p1 = new JPanel(); p1.setLayout(new GridLayout (2,2)); p1.add(new JLabel("Array Index")); p1.add(jtfIndex); p1.add(new JLabel("Array Element")); p1.add(jtfElement); //Create panel for button JPanel p2 = new JPanel(); p2.setLayout(new FlowLayout()); p2.add(jbtShow); //Set panels in frame getContentPane().setLayout(new BorderLayout()); getContentPane().add(p1,BorderLayout.CENTER); getContentPane().add(p2,BorderLayout.SOUTH); //Register Listener jbtShow.addActionListener(this); } //Main Method public static void main(String[] args) { int key; int[] list = new int[100]; for(int i = 0; i < list.length; i++) { list[i] = (int)(Math.random() * 100); } ArrayDemo frame = new ArrayDemo(); frame.pack(); frame.setVisible(true); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); frame.setSize(230, 120); } //The nitty gritty public void actionPerformed(ActionEvent e) { int key = (Integer.parseInt(jtfIndex.getText())); int[] list = new int[100]; int result = linearSearch(key, list); if (e.getSource() == jbtShow) if(result != -1) jtfElement.setText(String.valueOf(result)); else jtfElement.setText("Out of Bounds"); } public static int linearSearch(int key, int[] list) { for(int i = 0; i < list.length; i++) if (key == list[i]) return i; return -1; } }
|
 |
Adam Altmann
Greenhorn
Joined: Nov 15, 2003
Posts: 21
|
|
public void actionPerformed(ActionEvent e) { int key = (Integer.parseInt(jtfIndex.getText())); int[] list = new int[100]; int result = linearSearch(key, list); ... You're shadowing "list" (you've got two variables named "list"). You're performing the linearSearch on an array you've just created, not on the one you've populated with random numbers. Each element in THAT array (the "list" variable shown above) has been given the default value for int, which is zero. If you run the program and put a zero in the Array Index box, it'll match Array Element zero, since it's the first element of the array, and it has a zero in it.
|
SCJP 1.4
|
 |
 |
|
|
subject: Linear Searches
|
|
|