0

In a nutshell, my program allows the user to enter member details, which are then written to a text file on a new line. I am having trouble with the search. What I have to do is when a user types in a member ID in the text field, it looks through the text file and if that member ID is present, return the whole line.

This is my code (I have tried lots but don't know what to do under searchBtn:

    /**
     * Creates new form Members
     */
    public Members() {
        initComponents();
    }

    String[][] membersArray = new String[3][5]; 
    String lineRead;
    int i = 0;
    int j;

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")

    private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {                                        
        saveBtn.setEnabled(false);
        addBtn.setEnabled(true);

        try {
            FileWriter writer = new FileWriter("memberDetails.txt", true);
            writer.write(idTxt.getText() + "," + nameTxt.getText() + "," + addressTxt.getText() + "," + phoneTxt.getText() + "," + birthTxt.getText() + "\n");
            writer.close();
        }
        catch (IOException e){

        }
    }                                       

    private void addBtnActionPerformed(java.awt.event.ActionEvent evt) {                                       
        saveBtn.setEnabled(true);
        addBtn.setEnabled(false);

        idTxt.setText("");
        nameTxt.setText("");
        addressTxt.setText("");
        phoneTxt.setText("");
        birthTxt.setText("");
    }                                      

    private void searchBtnActionPerformed(java.awt.event.ActionEvent evt) {                                          
        try {
            FileReader reader = new FileReader("memberDetails.txt");
            BufferedReader buffer = new BufferedReader(reader);

            while((lineRead = buffer.readLine()) !=null) {

                for (i = 0; i < 2; i ++) {
                    for (j = 0; j < 5; j++) {
                        membersArray[i][j] = String.valueOf(lineRead.split(","));
                    }
                }
            }

            if (searchTxt.getText() == membersArray[i][0]) {
                // Print whole line
            }

            reader.close();
            buffer.close();
        }
        catch (IOException e) {

        }
    }                                         

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Members.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Members.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Members.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Members.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Members().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton addBtn;
    private javax.swing.JLabel addressLbl;
    private javax.swing.JTextField addressTxt;
    private javax.swing.JLabel birthLbl;
    private javax.swing.JTextField birthTxt;
    private javax.swing.JLabel idLbl;
    private javax.swing.JTextField idTxt;
    private javax.swing.JLabel nameLbl;
    private javax.swing.JTextField nameTxt;
    private javax.swing.JLabel phoneLbl;
    private javax.swing.JTextField phoneTxt;
    private javax.swing.JButton saveBtn;
    private javax.swing.JButton searchBtn;
    private javax.swing.JTextField searchTxt;
    // End of variables declaration                   
}
Jay Shankar Gupta
  • 5,918
  • 1
  • 10
  • 27
Sam
  • 1
  • `if(searchTxt.getText() == membersArray[i][0])`, note that you shouldn't being using `==` to compare strings. [How do I compare strings in Java?](https://stackoverflow.com/q/513832/5475891) – phflack Feb 20 '18 at 14:04
  • It also looks like you're writing the last line of the file to every position in the 2D array, is that intended? – phflack Feb 20 '18 at 14:09
  • Hi, sorry I have only been coding for around 2 months so I’m not great. No I don’t mean to write the last line to the 2d array, how do I get about not doing that? – Sam Feb 20 '18 at 14:24
  • If there's no other purpose to `membersArray`, I'd recommend removing it and using Johnny Mopp's answer. If it's used elsewhere, you may want to have a way to ensure the data read will be the right size, or use a List instead of arrays – phflack Feb 20 '18 at 14:26

1 Answers1

0

lineRead.split(","); returns an array, So calling String.valueOf(lineRead.split(",")); doesn't make sense.

Initialize a large array

String[][] membersArray = new String[20][5]; 

Read data and copy to array

int lineNumber = 0;
while((lineRead = buffer.readLine()) !=null) {
    // split line
    String [] parts = lineRead.split(",");
    // Save - but only if array is not full
    if (5 == parts.length && lineNumber < membersArray.length) {
        // Copy (could use System.arraycopy)
        membersArray[lineNumber][0] = parts[0];
        membersArray[lineNumber][1] = parts[1];
        membersArray[lineNumber][2] = parts[2];
        membersArray[lineNumber][3] = parts[3];
        membersArray[lineNumber][4] = parts[4];
        lineNumber += 1;

        // While we're here, check for match
        if (searchTxt.getText().equals(parts[0])) {
            // Fill in text boxes
            idTxt.setText(parts[0]);
            nameTxt.setText(parts[1]);
            addressTxt.setText(parts[2]);
            phoneTxt.setText(parts[3]);
            birthTxt.setText(parts[4]);
        }
    }
}
001
  • 13,291
  • 5
  • 35
  • 66
  • Thanks for this. But in our task we are asked to use an array. If you don't mind, how would I go about implementing membersArray in to this methodology? – Sam Feb 20 '18 at 14:29
  • Ok, but the problem with an array is they are fixed size - you need to know how large they will need to be when you create them. If you are only allowed to use Arrays (and not Lists), you need to either create a really big array (guessing at a size) or read through the file once, counting lines, then create the array, then read through again, saving data to array. – 001 Feb 20 '18 at 14:37
  • Thankyou so much! I've done this but it still isn't working, I've really got to use MOOC and start learning... Anyway, when you have time, would you be able to help write your solution but using an array? I keep getting a string[] cannot be converted to string[] method. – Sam Feb 20 '18 at 14:53
  • Edit: I have worked out my error. Thank you so much for the help! What I ended up doing was replacing "parts" with "memberArray" and made the size of the array a variable "count" where count gets incremented every time the user presses save. Thanks for the help. – Sam Feb 20 '18 at 15:02