File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Linear Searches Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Linear Searches" Watch "Linear Searches" New topic

Linear Searches

Marie Jeanne Thibault

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.
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
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(new JLabel("Array Element"));

//Create panel for button
JPanel p2 = new JPanel();
p2.setLayout(new FlowLayout());
//Set panels in frame
getContentPane().setLayout(new BorderLayout());
//Register Listener

//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.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("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

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
I agree. Here's the link:
subject: Linear Searches
It's not a secret anymore!