Java Program Compiles and Runs, but doesn't work
Posted
by
Richard Long
on Stack Overflow
See other posts from Stack Overflow
or by Richard Long
Published on 2012-04-15T23:25:10Z
Indexed on
2012/04/15
23:29 UTC
Read the original article
Hit count: 206
When I run this program I enter information in a text box, push the search button, but nothing happens. The program just sits there until I press Cntrl C to break it. It looks like it should work, but I can't figure out what is hanging the program up.
Here is the code: First class:
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class NameGameFrame extends JFrame
{
public static String name;
static JTextField textfield = new JTextField(20);
static JTextArea textarea = new JTextArea(30,30);
public static String num;
public static String [] fields;
public static int [] yearRank;
public static boolean match;
public static int getInts, marker, year, max;
public static void main( String[] args)
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Name Game");
frame.setLocation(500,400);
frame.setSize(800,800);
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JLabel label = new JLabel("Enter the Name or Partial Name to search:");
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(2,2,2,2);
panel.add(label,c);
c.gridx = 0;
c.gridy = 1;
panel.add(textarea,c);
JButton button = new JButton("Search");
c.gridx = 1;
c.gridy = 1;
panel.add(button,c);
c.gridx = 1;
c.gridy = 0;
panel.add(textfield,c);
frame.getContentPane().add(panel, BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
name = textfield.getText();
java.io.File file = new java.io.File("namesdata.txt");
try
{
Scanner input = new Scanner(file);
num = input.nextLine();
NameRecord nr = new NameRecord(name);
while (input.hasNext())
{
if(match = num.toLowerCase().contains(name.toLowerCase()))
{
nr.getRank();
nr.getBestYear(marker);
}
}
}
catch(FileNotFoundException e)
{
System.err.format("File does not exist\n");
}
textarea.setText(fields[0]);
}
});
}
}
This is the second class:
import java.io.*;
import java.util.*;
public class NameRecord
{
public NameRecord( String name)
{
}
public static int getBestYear(int marker)
{
switch (marker)
{
case 1:
year = 1900;
break;
case 2:
year = 1910;
break;
case 3:
year = 1920;
break;
case 4:
year = 1930;
break;
case 5:
year = 1940;
break;
case 6:
year = 1950;
break;
case 7:
year = 1960;
break;
case 8:
year = 1970;
break;
case 9:
year = 1980;
break;
case 10:
year = 1990;
break;
case 11:
year = 2000;
break;
}
return year;
}
public static int getRank()
{
fields = num.split(" ");
max = 0;
for (int i = 1; i<12; i++)
{
getInts = Integer.parseInt(fields[i]);
if(getInts>max)
{
max = getInts;
marker = i;
}
}
return max;
}
}
© Stack Overflow or respective owner