• 0

major java problem


Question

i really need to get a problem fix tonight, so im hoping a late night programmer will see this. i made a database program that uses flat files storage. let me post the code (its messy):

import java.io.*;
import java.util.StringTokenizer;

class DataBase
{
 private String [] name;
 private String [] addr;
 private String[] phoneNum;
 private static int num;
 private static BufferedReader fileIn;
 private static PrintWriter fileOut;

 public static void main (String[] args) throws IOException
 {
  
  String fileName = "file2.txt";
  String str;
  DataBase list = new DataBase();
  
  BufferedReader cin = new BufferedReader (new InputStreamReader (System.in));
  
  System.out.print("How many contacts? ");
  str = cin.readLine();
  num = Integer.parseInt(str);
  createOutputFile(fileName);
  addcontact(num, cin);
   /* if (num > 1)
     sort();*/
  list.parse(fileName);
  list.displayList(num);
  System.out.print("Do you want to update the list? ");
  str = cin.readLine();
/*  if (str.equals("yes"))
  {
   num = 0;
   while(l < num)
   {
       list.update(num);
    num++;
   }  
  }*/
  System.out.print("Do you want to search a person? ");
  str = cin.readLine();
  if (str.equals("yes"))
  {
   System.out.print("Please enter the name of the person.");
   str = cin.readLine();
   String pNum=list.find(str);
   
   System.out.print("The phone number is " + pNum);
           
           
         }    
   
  
 }

  private static void createOutputFile(String fileName)
  {
    try
    {
      fileOut = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
    }
    catch (IOException e)
    {
    }
  }
  
  private static void openInputFile(String fileName)
  {
    try
    {
      fileIn = new BufferedReader(new FileReader(fileName));
    }
    catch (FileNotFoundException e)
    {
    }
  } 
 public DataBase()
 {
  name = new String [10];
  addr = new String [10];
  phoneNum = new String [10];
 }
  private void parse(String fileName) throws IOException
  {
 	 fileIn = new BufferedReader(new FileReader(fileName));
 	 String str;
 	 while ((str = fileIn.readLine()) != null)
 	 {
    int j = 0;
    StringTokenizer r = new StringTokenizer (str, ",");
        String strname = r.nextToken();
        String straddr = r.nextToken();
        String strphone = r.nextToken();
        name[j] = strname;
        addr[j] = straddr;
        phoneNum[j] = strphone;
        j++;
    }    
    
    fileIn.close();

  }   

 public static void addcontact (int index, BufferedReader cin) throws IOException
 {
  String str;
  String nameread;
  String addrread;
  String phoneNumread;
  fileOut = new PrintWriter(new BufferedWriter(new FileWriter("file.txt")));
  for(int h = 0; h < index; h++)
  {
  System.out.print("Name:  ");
  nameread = cin.readLine();
  nameread = nameread.trim();
  System.out.print("Address:  ");
  addrread = cin.readLine();
  addrread = addrread.trim();
  System.out.print("Phone number");
  phoneNumread = cin.readLine();
  phoneNumread = phoneNumread.trim();
  String line = nameread + "," + addrread + "," + phoneNumread;
  
  fileOut.println(line);}
  fileOut.close();
 }

 public void displayList (int n)
 {
  String s1, s2, s3;
  
  System.out.println("\n Name        Address         Phone_Number \n");
  
  for (int k = 0; k < n; k ++)
  {
   s1 = (name[k] + "           ").substring(0, 10);
   s2 = (addr[k] + "           ").substring(0, 10);
   System.out.println(s1 + " " + s2 + " " + phoneNum[k]);
  }
  
 }


}

it stores name, address, and phone number in a line separated by commas. the parser uses stringtokenizer to separate the elements, and puts them in separate arrays. however, it only seems parse the last line. the info in this line is put into the array positions of 0. it is a problem with the parse method, but i dont see it. anybody know what's wrong?

Link to comment
Share on other sites

11 answers to this question

Recommended Posts

  • 0

Yep...

while ((str = fileIn.readLine()) != null)
  {
   int j = 0;
 ...
       name[j] = strname;
       addr[j] = straddr;
       phoneNum[j] = strphone;
       j++;
   }    

you keep initializing j to 0, so it only stores in the first position for each line. Declare and initialize int j = 0; outside of the loop.

Link to comment
Share on other sites

  • 0

yep, that's the only problem I right now.

int j = 0;

while ((str = fileIn.readLine()) != null)

{

StringTokenizer r = new StringTokenizer (str, ",");

String strname = r.nextToken();

String straddr = r.nextToken();

String strphone = r.nextToken();

name[j] = strname;

addr[j] = straddr;

phoneNum[j] = strphone;

j++;

}

Link to comment
Share on other sites

  • 0

thanks for the replies. i fixed that up last night, but still have one problem...with the sorting method. its not sorting the entrie in ascending order. heres the updated code. that particular method is at the end.

//Import the necessary classes
import java.io.*;
import java.util.StringTokenizer;

public class DataBase {
	private String [] name;
	private String [] addr;
	private String[] phoneNum;
	private static int num;
	private static BufferedReader fileIn; //Allows for a stream
	private static PrintWriter fileOut; //Allows for a stream

	public static void main (String[] args) throws IOException {
  String fileName = "contacts.txt"; //Name of database
  DataBase list = new DataBase();

  BufferedReader cin = new BufferedReader (new InputStreamReader (System.in)); //Begin reading inputs

  System.out.print("How many contacts? "); //How many people are going to be catalogued?
  String str = cin.readLine();
  num = Integer.parseInt(str);
  createOutputFile(fileName); //Physically write the database
  addContact(num, cin); //Call to the method that adds entrues
  openInputFile(fileName); //Open the file for display
  list.parse(fileName); //Call to method that will parse database
  if (num > 1) //No need to sort if we have 1 entry
 	 list.sort(); //Call to method that will sort database
  list.displayList(num); //Call to method that will display entries
  System.out.print("Do you want to update the list? "); //Do they want to modify data?
  str = cin.readLine();
  if (str.equalsIgnoreCase("yes")) { //Check their response
 	 openInputFile(fileName); //Open file for modification
 	 int l = 0;
 	 while (l < num) {
    list.update(l, fileName); //Call to modifier method
    l++;
 	 } 
  } 
  System.out.print("Do you want to search a person? "); //Would they like to search the database?
  str = cin.readLine();
  if (str.equalsIgnoreCase("yes")) { //Check their response
 	 System.out.println("Please enter the name of the person: "); //Who would they like to search?
 	 str = cin.readLine();
 	 String pNum = list.find(str); //Call to method that finds their request

 	 System.out.println("The phone number is " + pNum); //Queried phone number
  } 
	} 


	public DataBase() { //Constructor for our object of arrays
  name = new String [10];
  addr = new String [10];
  phoneNum = new String [10];
	} 
	private void parse(String fileName) throws IOException { //Method that parses database
  String str;
  int j = 0;
  while ((str = fileIn.readLine()) != null) { //Make sure we haven't reached the end of the database
 	 StringTokenizer r = new StringTokenizer(str, ","); //Parse a line with delimiters

 	 while (r.hasMoreTokens()) { //This will take each parsed token and put in an element of an array
    String strname = r.nextToken();
    String straddr = r.nextToken();
    String strphone = r.nextToken();
    name[j] = strname;
    addr[j] = straddr;
    phoneNum[j] = strphone;
    j++;
 	 } 
  } 

  fileIn.close(); //Close the file access because we are done
	} 

	public static void addContact (int index, BufferedReader cin) throws IOException { //Method that adds an entry
  String str;
  String nameread;
  String addrread;
  String phoneNumread;
  for(int h = 0; h < index; h++) { //Takes the inputted information, and puts in a line separated by commas
 	 System.out.print("Name:  ");
 	 nameread = cin.readLine();
 	 nameread = nameread.trim();
 	 System.out.print("Address:  ");
 	 addrread = cin.readLine();
 	 addrread = addrread.trim();
 	 System.out.print("Phone number:  ");
 	 phoneNumread = cin.readLine();
 	 phoneNumread = phoneNumread.trim();
 	 String line = nameread + "," + addrread + "," + phoneNumread;

 	 fileOut.println(line); //Store the line in the db
  } 
  fileOut.close();
	} 


	public void sort (String a[]) { //The actual sorting method
  int i, iMax, n, diff;
  String aTemp = null;
  try
  {
 	 for (n = a.length; n >= 2; n--) {
    iMax = 0;

    for (i = 1; i < n; i++) {
   	 diff = a[i].compareTo(a[iMax]);
   	 if (diff > 0)
      iMax = i;
    } 

    aTemp = a[iMax]; //Arrange the names and the corresponding phone numbers and addresses
    a[iMax] = a[n-1];
    a[n-1] = aTemp;

    aTemp = addr [iMax];
    addr[iMax] = addr[n-1];
    addr[n-1] = aTemp;

    aTemp = phoneNum[iMax];
    phoneNum[iMax] = phoneNum[n-1];
    phoneNum[n-1] = aTemp;
 	 } 
  } 
  catch(Exception e) {
 	 //System.out.println("Error is: " + e);
 	 //Uncomment the above if you want to show the user the error
  } 
	} 
}

Link to comment
Share on other sites

  • 0

Your outer for loop is not iterating through the entire array. It exits when n == 2, so your last 2 elements aren't being sorted.

Try this and see if it works.

 for( n = a.length-1; n > 0; n--)    

Link to comment
Share on other sites

  • 0
Your outer for loop is not iterating through the entire array. It exits when n == 2, so your last 2 elements aren't being sorted.

Try this and see if it works.

 for( n = a.length-1; n > 0; n--)    

nope...didnt work

Link to comment
Share on other sites

  • 0
Its must be so nice of everyone to pitch in and do your homework for you.

actually...its not homework. also...if youre implying that people are doing the work for me...youre far from the truth. as you can see, i have done all of the code; however, it is plagued by a few mistakes that i am seeking help on correcting. so...we come to the conclusion that no one is doing this program for me as i have done all of it (with the exception of some corrections).

Link to comment
Share on other sites

  • 0

OK. I think I'm thoroughly confused now that I've looked at your entire code.

Your use of global variables ( the ones above the main method ) confuses the code. Try to eliminate them.

A couple of suggestions. If you want to be able to reuse class Database, take the main out of it and put it in another class that will use the Database class. You should also keep all user prompts within the using class (e.g. TestDB).

public class TestDB
{
  public static void main(String[] args)
  {
    ... testing/usage code here
   }
}

// in another file
public Database
{
  // member declarations
  Database()
  {
     // constructor code...
  }
} // etc.

Also, to make this app a little easier to understand, think about the object heirarchy. A database is a collection of records. A record, in this case, has a name, address, and number.

I would have a record class ( named whatever you want, like Entry or something ) and a Database class that has an array of records and the methods to sort, find, edit, print, etc.

Since you are probably going to want to have the phonebook sorted all the time ( just an assumption since I've never seen a phonebook that wasn't sorted alphabetically ), try using the binary search method to insert new records and find records for editing, printing, deleting, etc. The performance will be dramatically increased over having to sort after each insertion (theoretically).

You may also want to make your Database and the record classes Serializable to ease saving of state.

I know this doesn't address your question, but your code as it is written is difficult to follow, and is, from an OO perspective, poorly designed.

I can give you examples of using a binary search if you'd like. If you follow my advice, I know it means rewriting your entire program, but I think you'll learn a lot from doing so and have a much more robust program.

Link to comment
Share on other sites

  • 0

Search on the web for a simple sorting algorithm called selection sort. Your sort looks similar to it but not exactly and since you're having sorting problems, getting that algorithm will probably fix your problems. Also, java.util.Arrays has some sorting methods.

I have one comment that would have made things easier for you, but since you've done a lot of the code already, you may want to keep this in mind for your next assignment instead. Your database could be much more object-oriented if you created an object class with a person's name, address and phone number and stored that in an array instead. That would make things easier to manage and you wouldn't have to run the same code three times (ie: code to delete a name, code to delete an address, code to delete a phone number).

Link to comment
Share on other sites

  • 0
OK. I think I'm thoroughly confused now that I've looked at your entire code.

Your use of global variables ( the ones above the main method ) confuses the code. Try to eliminate them.

A couple of suggestions. If you want to be able to reuse class Database, take the main out of it and put it in another class that will use the Database class. You should also keep all user prompts within the using class (e.g. TestDB).

public class TestDB
{
 ?public static void main(String[] args)
 ?{
 ? ?... testing/usage code here
 ? }
}

// in another file
public Database
{
 ?// member declarations
 ?Database()
 ?{
 ? ? // constructor code...
 ?}
} // etc.

Also, to make this app a little easier to understand, think about the object heirarchy. A database is a collection of records. A record, in this case, has a name, address, and number.

I would have a record class ( named whatever you want, like Entry or something ) and a Database class that has an array of records and the methods to sort, find, edit, print, etc.

Since you are probably going to want to have the phonebook sorted all the time ( just an assumption since I've never seen a phonebook that wasn't sorted alphabetically ), try using the binary search method to insert new records and find records for editing, printing, deleting, etc. The performance will be dramatically increased over having to sort after each insertion (theoretically).

You may also want to make your Database and the record classes Serializable to ease saving of state.

I know this doesn't address your question, but your code as it is written is difficult to follow, and is, from an OO perspective, poorly designed.

I can give you examples of using a binary search if you'd like. If you follow my advice, I know it means rewriting your entire program, but I think you'll learn a lot from doing so and have a much more robust program.

I second that. Your program is pretty hard to follow and it's quite possible you'll lose marks if your teacher is expecting your program to be more object-oriented. Off the top of my head, you'd have 3 classes - one for the main program, one for the database, and one for an entry in the database. But like I said before, that's something you may want to keep in mind for your next assignment.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.