做的是一个通讯录页面系统,用于储存姓名和电话
str里面我通过input存入过了一些内容,并且还把内容传入到了文件中
public void input(JTextField b1,JTextField b2 ) {
Person a=new Person();
a.setName(b1.getText());
a.setTelnumber(b2.getText());
str.add(a);
}
public void writeFile(String filename) {
FileWriter fw =null;
try{
fw=new FileWriter("D:/ss.txt",true);
for(int i=0;i<str.size();i++)
{
fw.write(str.get(i).toString());
fw.write("\n");
}
fw.flush();
fw.close();
JOptionPane.showMessageDialog(null, "保存成功");
}catch (Exception ex) {
ex.printStackTrace();
}
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==a3) {
a.input(a1,a2);
JOptionPane.showMessageDialog(null,"录入成功");
}
if(e.getSource()==a4) {
a.writeFile("D:/ss.txt");
}
}
问题就在于 查找名字来对应输出电话号码时,无论输入了什么名字,结果都是null
ArrayList<Person>str=new ArrayList<Person>();
public String searchByName(String name) {
for(int i=0;i<str.size();i++)
{
if(name.equals(str.get(i).getName()))
{
return str.get(i).getTelnumber();
}
}
return null;
下面是页面设置和搜索过程
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class Search extends JFrame implements ActionListener{
PhoneBook a=new PhoneBook();
JButton b1=new JButton("确定");
JTextField a3=new JTextField(20);
JTextField a4=new JTextField(20);
Search(){
JLabel tt=new JLabel("请输入姓名:");
JLabel tt1=new JLabel("电话号码为:");
setSize(500,500);
setBounds(300,300,300,300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container s1= getContentPane();
s1.setLayout(null);
s1.add(tt);
s1.add(a3);
s1.add(tt1);
s1.add(a4);
s1.add(b1);
tt.setBounds(10,40,100,18);
a3.setBounds(10,80,100,18);
tt1.setBounds(10,120,100,18);
a4.setBounds(10,160,100,18);
b1.setBounds(10, 200, 100,18);
setVisible(true);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==b1) {
String name=a3.getText();
String tel=a.searchByName(name);
System.out.println(tel);
a4.setText(tel);
}
}
}
小白一个,有没有大神告诉我一些思路或者告诉我错在哪了!!