0
如何使程序搜索字符串的文件并打印出该行? 我想要做的是创建一个地址簿类型的东西。我很抱歉,如果我的代码很混乱,因为这是我以前做过的第一次。对于这种事情,HashMap会更好吗?如果是这样,有可能有多个值附加到相同的密钥?如何使用缓冲读取器在文件中搜索字符串
public class contats extends JFrame {
JLabel nameLabel;
JLabel phoneLabel;
JLabel notesLabel;
JLabel searchLabel;
JTextField name;
JTextField phone;
JTextField notes;
JTextField searchField;
JButton add;
JButton search;
public contats() {
setLayout(new FlowLayout());
nameLabel = new JLabel("Name: ");
add(nameLabel);
name = new JTextField(15);
add(name);
phoneLabel = new JLabel("Number: ");
add(phoneLabel);
phone = new JTextField(15);
add(phone);
notesLabel = new JLabel("Notes: ");
add(notesLabel);
notes = new JTextField(10);
add(notes);
add = new JButton("Add Contact");
add(add);
searchLabel = new JLabel("search");
add(searchLabel);
searchField = new JTextField(15);
add(searchField);
search = new JButton("Search");
add(search);
event e = new event();
add.addActionListener(e);
search.addActionListener(e);
}
public class event implements ActionListener{
public void actionPerformed(ActionEvent e) {
if (e.getSource() == add){
try {
String[] con = {name.getText(),phone.getText(),notes.getText()};
BufferedWriter bw = new BufferedWriter(new FileWriter("peewee.txt", true));
for(String s : con){
bw.newLine();
bw.write(s);
}
bw.close();
}catch(Exception ex){
JOptionPane.showMessageDialog(null, "blerr");
}
} else if(e.getSource() == search){
try{
String input = search.getText();
String file;
String searchArray[];
BufferedReader br = new BufferedReader(new FileReader ("peewee.txt"));
while((file = br.readLine())!= null){ // this is where i need the help??
if(file == input){
System.out.println(input);
}
}
br.close();
} catch(Exception ex) {
JOptionPane.showMessageDialog(null, "sdfadsfsdf");
}
}
}
}
public static void main(String[] args) {
contats gui = new contats();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(300, 300);
gui.setTitle("Cobtacts");
gui.setVisible(true);
}
}
尝试坚持Java约定,并用大写字母开始类名称! –
首先,阅读Java中的字符串比较。 http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java/513839#513839不知道如果这是唯一的错误,但首先解决这个问题。 – Keith
整个GUI的东西是完全不相关的。你需要了解String比较。去吧,查找java.lang.String的javadoc! – Ingo