【发布时间】:2012-04-27 08:48:36
【问题描述】:
当我运行这个程序时,我在文本框中输入信息,按下搜索按钮,但没有任何反应。程序就在那里,直到我按下 Cntrl C 来打破它。看起来它应该可以工作,但我不知道是什么让程序挂起。
代码如下: 头等舱:
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]);
}
});
}
}
这是第二课:
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;
}
}
【问题讨论】:
-
您好 Richard,请考虑使用调试器来调试您的代码并跟踪其执行情况。充其量,您可能会自己找到答案,最坏的情况是,它至少会为您提供更多信息,以便在此处发布,这将有助于使问题更加具体。
-
你有没有给
fields[]数组赋值过? -
糟糕、丑陋的代码。如果您将 getBestYear 放入 Map 并使用标记作为键并使用年份作为值进行查找,那么 getBestYear 将是一个小方法。
-
为什么要删除问题中的代码?我已经为你取消删除了。