4 Replies Latest reply: Jan 6, 2005 2:10 PM by 807596 RSS

    example of storing information in a fixed size array and searching it

    807596
      Hello all I'm new to java and I'll like to get an example of storing elements in a fixed array using command line or JOptionPane, and then searching the array to find out, for example which customer first name is John. Can someone help me with an example or point me to where I can find good simple information on this? Also can I use methos to store in the array a new instance of a new customer everytime a customer is added?
        • 1. Re: example of storing information in a fixed size array and searching it
          807596
          I'm pretty new to Java, myself. I have been critisized in this forum for not observing the naming conventions so it is with some trepication that I offer you this example, but here goes.

          I wrote a program to keep track of when my dogs' and cats' shots were due on a PDA. I made it general so the data file "says" what each column is. All the data is kept in a comma delimited text file as follows:
          the first row says how many entries there are;
          the 2nd row lists the column headings (name, breed, rabies due, distemper due, etc. in my case);
          the subsequent rows have the pertinent records.

          Again, I am sure this is not a particularly good program; it works for me, however:
          import java.awt.*;
          import java.awt.event.*;
          import java.io.*;
          import java.util.*;
          import java.text.*;
          
          class dandc extends Frame implements ActionListener {
          //    class data
          static TextField pval;
          static int numPets, row, numfields;
          static String petDb[][], linelm[], hdrow;//petDb holds the data
          static Choice dparm=new Choice();
          static Choice pname=new Choice();
          static String fileIn = new String("d&c.csv");//d&c.csv is my data text file
          static Font dc = new Font("Serif", Font.BOLD,15);
          //    main method
               public static void main(String args[]) throws IOException {
               //call constructor
                   if (args.length!=0) fileIn=args[0];
                   dandc dc1 = new dandc();
               }
          //   constructor method
                public dandc() throws IOException {
               //Initilaize
                   BufferedReader dbFile = new BufferedReader(new FileReader(fileIn));
                   numPets = Integer.parseInt(dbFile.readLine());//read the first row and find out how many records there are
                   String line=dbFile.readLine();
                   hdrow = line;//header row
                   int nf = 0;
                   int ix = 0;
                   while (hdrow.indexOf(",",ix+1)>-1) {
                        ix = hdrow.indexOf(",",ix+1);
                        if (ix==-1) {break;}
                        nf++;
                   }
                   numfields=nf+1;
                   petDb = new String[numPets+12][numfields];//leave extra room for new records
                   linelm = new String[numfields];
                   parseLine(line, linelm);
                   for (int i=0; i<numfields; i++) {
                       dparm.add(linelm);
          }//I use "Choice" objects with a "new" item in the record choice
          dparm.addItemListener(new ItemListener(){
          public void itemStateChanged(ItemEvent e) {
          int srix = pname.getSelectedIndex();
          int scix = dparm.getSelectedIndex();
          pval.setText(petDb[srix][scix]);
          }
          });
          row = 0;
          while ((line=dbFile.readLine()) != null) {
          parseLine(line, linelm);
          for (int i=0; i<numfields; i++) {petDb[row][i]=linelm[i];}
          row++;
          }
          dbFile.close();
          for (int i=0; i<row; i++) {
          pname.add(petDb[i][0]);
          }
          pname.addItemListener(new ItemListener(){
          public void itemStateChanged(ItemEvent e) {
          if (pname.getSelectedItem()=="New") dparm.select(0);
          int srix = pname.getSelectedIndex();
          int scix = dparm.getSelectedIndex();
          pval.setText(petDb[srix][scix]);
          }
          });
                    setTitle("Data Keeper");
                    addWindowListener(new WindowAdapter() {
                         public void windowClosing(WindowEvent e) {
                              System.exit(0);
                         }
                    });
          ScrollPane sp = new ScrollPane();
          Panel p0 = new Panel();
          p0.setLayout(new GridLayout(0,1));
          pname.add("New");
          //pname.setFont(dc);
          p0.add(pname);
          p0.add(dparm);
          pval = new TextField();
          pval.setFont(dc);
          p0.add(pval);
          Button chk = new Button("update");
          chk.addActionListener(this);
          p0.add(chk);
                              //menu
                    MenuBar mb1=new MenuBar();
                    this.setMenuBar(mb1);
                    Menu m1=new Menu("File");
                    MenuItem f12=new MenuItem("addRec");
                    f12.addActionListener(this);
                    MenuItem f13=new MenuItem("save");
                    f13.addActionListener(this);
                    MenuItem f14=new MenuItem("Quit");
                    f14.addActionListener(new ActionListener() {
                         public void actionPerformed(ActionEvent e) {
                              System.exit(0);
                         }
                    });
                    Menu m2=new Menu("Slct");
                    MenuItem f21=new MenuItem("showNext");
                    f21.addActionListener(this);
                    MenuItem f22 = new MenuItem("+1Yr");
                    f22.addActionListener(this);
                    MenuItem f23 = new MenuItem("delRec");
                    f23.addActionListener(this);
                    m1.add(f12);
                    m1.add(f13);
                    m1.add(f14);
                    m2.add(f21);
                    m2.add(f22);
                    m2.add(f23);
                    mb1.add(m1);
                    mb1.add(m2);
          //
          sp.add(p0);
          sp.setSize(200,150);
          add("Center", sp);
                    pack();
                    show();
          }
          // menu event handler
               public void actionPerformed(ActionEvent e) {
                    Object esrc = e.getSource();
          // addRec needs to be performed after a new record has been defined
               if (esrc instanceof MenuItem && e.getActionCommand()=="addRec") {
          pname.remove("New");
          pname.add(petDb[row][0]);
          pname.add("New");
          numPets++;
          row++;
                    }
          // update adds field information from the TextField to the array
                    else if (esrc instanceof Button && e.getActionCommand()=="update") {
          int srix = pname.getSelectedIndex();
          int scix = dparm.getSelectedIndex();
          petDb[srix][scix] = pval.getText();
          }
          //showNext may be only useful for me; tells me which animal is due next
                    else if (esrc instanceof MenuItem && e.getActionCommand()=="showNext") {
          int scix = dparm.getSelectedIndex();
          int srix = 0;
          Date d = new Date();
          Date d2 = new Date();
          SimpleDateFormat df = new SimpleDateFormat("MM/dd/y");
          try {d = df.parse(petDb[0][scix]);}
          catch (ParseException pe) {System.out.println(pe);}
          for (int i=1; i<numPets; i++) {
          try {d2=df.parse(petDb[i][scix]); }
          catch (ParseException pe) {continue;}
          if (d.after(d2)) {
               d=d2;
               srix=i;
          }
          }
          pname.select(srix);
          pval.setText(petDb[srix][scix]);
          }
          //likewise; adds a year to today and puts it in the TextField
                    else if (esrc instanceof MenuItem && e.getActionCommand()=="+1Yr") {
          int scix = dparm.getSelectedIndex();
          Calendar currentDate = Calendar.getInstance();
          int iyr = currentDate.get(Calendar.YEAR) +1;
          int imn = currentDate.get(Calendar.MONTH)+1;
          int idy = currentDate.get(Calendar.DATE);
          pval.setText(imn+"/"+idy+"/"+iyr);
          }
                    else if (esrc instanceof MenuItem && e.getActionCommand()=="delRec") {
          int srix = pname.getSelectedIndex();
          numPets--;
          for (int i=0; i<numfields-1; i++) {petDb[srix][i]=petDb[row][i];}
          row--;
          pname.remove(srix);
          pval.setText("");

          }
          //save puts the array back in the text file
                    else if (esrc instanceof MenuItem && e.getActionCommand()=="save") {
          try {PrintWriter outF = new PrintWriter(new FileWriter (fileIn,false));
                             outF.println(numPets);
                             outF.println(hdrow);
                             for (int i=0;i<row;i++) {
                                 for (int j=0; j<numfields-1; j++) {
                                     outF.print(petDb[i][j]+",");
          }
          outF.print(petDb[i][numfields-1]+"\n");
          }
          outF.close();
          }
          catch (IOException eio) {System.out.println(eio);}
                    }
               }
               //method to parse comma delimited line -- PDA has limited tokenizer stuff
               public static void parseLine(String line, String linelm[]) {
          int arrix = 0;
          int lix = 0;
          while (line.indexOf(",")>-1) {
          lix = line.indexOf(",");
          if (lix==-1) break;
          linelm[arrix]=line.substring(0,lix);
          line=line.substring(lix+1);
          arrix++;
          }
          linelm[arrix]=line;
          }
          }
          • 2. Re: example of storing information in a fixed size array and searching it
            807596
            Hello rrashkin,
            this is a very good programm, however a bit too lengthy and it uses the awt packages which I've not touched as yet. I'm doing a simple program in swing or command line. Very much thanks for your good programm. I'm definitly keeping it for further reference. Any more help?
            • 3. Re: example of storing information in a fixed size array and searching it
              807596
              I guess it depends on what you are trying to do. I still think you want a 2-d array; that's a pretty simplistic database representation. Do you want to keep the information in a file? If so, I obviously thought my way (number of records, header record, data records) was the most efficient (that doesn't mean that it is). What specifically do you want to do (algorithmically)?
              • 4. Re: example of storing information in a fixed size array and searching it
                807596
                Thank you for your kind concerns but I got an example from a search, I also incorporated some of your ideas :)
                thanks a million