我需要从用户那里获取每个人的姓名和成绩的输入,将具有相应成绩的人名保存到数组中,以便稍后可以按姓名或成绩进行搜索。 这是我到目前为止所得到的
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class Grades extends JFrame
{
String names;
int results, count;
int a;
//declare Buttons
private JTextField t1, name, grades;
private JLabel lbl1, namelbl, gradelbl;
//constructor
public Grades()
{
super("Grades");
Container c = getContentPane();
c.setLayout(new FlowLayout());
lbl1 = new JLabel("Please enter a number of results");
c. add(lbl1);
t1 = new JTextField (2);
c. add(t1);
namelbl = new JLabel("Please enter student's name");
c. add(namelbl);
name = new JTextField (10);
c. add(name);
gradelbl = new JLabel("Please enter student's grade");
c. add(gradelbl);
grades = new JTextField (10);
c. add(grades);
//create an instance of inner class ButtonHandler
//to use for button event handling
ButtonHandler handler = new ButtonHandler();
t1.addActionListener(handler);
name.addActionListener(handler);
grades.addActionListener(handler);
setSize(400, 400);
setVisible(true);
}
public static void main (String args [])
{
Grades app = new Grades();
app.addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
//inner class for button event handling
private class ButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
Container c = getContentPane();
if(e.getSource() == t1)
{
a = Integer.parseInt(t1.getText());
if (a < 2 || a > 25)
{
JOptionPane.showMessageDialog(null, "You entered wrong value. Please re- enter");
t1.requestFocusInWindow();
t1.setText("");
a = Integer.parseInt(t1.getText());
}
name.requestFocusInWindow();
}
if(e.getSource() == name)
{
names = name.getText();
grades.requestFocusInWindow();
grades.setText("");
}
if(e.getSource() == grades)
{
results = Integer.parseInt(grades.getText());
if(results < 0 || results > 100)
{
JOptionPane.showMessageDialog(null, "You entered wrong value. Please re- enter");
grades.requestFocusInWindow();
grades.setText("");
a = Integer.parseInt(t1.getText());
}
else
{
name.requestFocusInWindow();
name.setText("");
System.out.println(names + " " + results);
}
}
}
}
}
答案 0 :(得分:0)
要将它们存储在一个数组中,您只需将它们放在第一位。
例如,names数组只是创建一个新数组:
'String[] namelist = new String[numofnames];'
然后搜索它只需使用for循环并检查索引以查找您要查找的字符串名称。检查它是否匹配。
实施例
for(int x = 0; x<numofnames; x++)
{
name.toLowerCase();
namelist.toLowerCase();
if(name.equals(namelist[x])
return x; //return whatever you need
}
这应该可以解决这个问题。