Status
Not open for further replies.

NedKelly

Wise, Aged Ars Veteran
165
Hi folks, my program is running well except I cannot add a new record to the team. I think its reading the null and zero values as a record and wont let me and the other records. It is telling me that there are more that 11 records which is its limit and so it wont add anymore. In fact there are only 7 records and the others were initiated as the array loads into memory, I then do all the alterations in the array before saving to file.

Your help would be greatly appreciated
Regards Ned.

code:<HR>
Code:
//Program written by Michael Kelly
//Started on the 19/9/01<P>import java.io.*;<P>class Athletics
{
  	public static void main(String[] args) throws IOException
  	{
   		int x; // how many records in the file, every 5 lines of data = one record
    	boolean done = false;
  		//Initiate the array
    	AthletesID[] athId = new AthletesID[11];
    	for (int i = 0; i < 11; i++)
      		athId[i] = new AthletesID(); 
     		//Check to see if the file exists
     		checkFile();
     		//Load the file into the array
     		x = onLoad(athId);
     		System.out.println("\tNumber of Records= "+ x);<P>    	while (!done)
			{ //Welcome the user
				
				System.out.println("\t---------------------------------------------");
				System.out.println("\tWelcome to the Ned Kelly Athletics Team. ");
				System.out.println("");
				System.out.println("\tPlease enter the events as 100m, 200m, 1000m.");
				System.out.println("\tThe maximum number of members is eleven athletes.");
				System.out.println("\t---------------------------------------------");
				System.out.println("");
				System.out.println("\tChoose an option number, then press enter. ");
				System.out.println("");<P>				char menu;
				//Display the menu
				System.out.println("\t1: New member. ");
				System.out.println("\t2: Edit entry. ");
				System.out.println("\t3: Delete entry. ");
				System.out.println("\t4: Display data. ");
				System.out.println("\t5: Save file. ");
				System.out.println("\t6: Exit program. ");
				
				menu=(char) System.in.read();
		switch (menu) //Choose from input the selection from the switch statement
			{
			  	case '1':  	NewMember(x, athId);
							break;
				case '2': try
           			{
              			editEntry(athId);
					}
					catch(IOException e)
					{
						System.out.println("editEntry IOException"+e);
					}
					break;<P>				case '3': try
					{
						deleteEntry(athId);
					}
					catch(IOException e)
					{
						System.out.println("deleteEntry IOException "+e);
					}
					break;<P>         		case '4':  try
             		{
              			displayData(athId);
                    }
                    catch(IOException e)
                    {
                        System.out.println("displayData IOException"+e);
                    }
					break;<P>				case '5':  try
					{
						Save(athId);
					}
					catch (IOException e)
					{
						System.out.println("Save IOException "+e);
					}
					break;
					
				case '6':  try
					{
						exitProgram(athId);
						done = false;
					}
					catch (IOException e)
					{
						System.out.println("exitProgram IOException "+e);
					}
					break;
       		}<P>    	}
  	}<P>public static void checkFile() throws IOException
 	{ //Check to see if the file exists
  	File dataFile = new File ("a:events.dat");
  	if (!dataFile.exists())
  		{
   			System.out.println ("File does not exist.");
  			System.exit(1);
  		}
 	}
public static int onLoad(AthletesID[] athId) throws IOException
   {
    	FileReader fr = new FileReader("a:events.dat");
     	BufferedReader br = new BufferedReader(fr);
    	String line;
     	int num=0; // Counter to store how many records in your file, every 5 lines = one record
     	int y=0, id=0, age=0;
     	double time=0;<P>     	while((line = br.readLine()) != null)
     		{
      			y = y + 1;
      			if (y == 1)
      		{
           		id = Integer.parseInt(line);
         		athId[num].setathNum(id);
    		}
    		if (y == 2)
    			athId[num].setathName(line);
   			if (y == 3)
        		{
         			age = Integer.parseInt(line);
    				athId[num].setathAge(age);
   				}
   			if (y == 4)
    			athId[num].setathEvent(line);
   			if (y == 5)
   				{
    				time = Double.parseDouble(line);
    				athId[num].setathTime(time);
         			num = num + 1;
         			y = 0;
        		}
		    }
      		fr.close();
      		return num; // how many records, every 5 lines = one record
   	}
public static void NewMember(int num, AthletesID[] athId) throws IOException
	{
    //Declare and intialise variables
    char rec;
    int id=0, age=0;
    String name=null, event=null;
    double time=0;
    boolean done = false;<P>  	//Set num to step through the array
  	num = num + 1;
  		//While not false take data for the new member
     	while(!done)
			{
			
				System.out.print("Athletes ID: ");
				System.in.read(); System.in.read();
				id=DataIn.readLineInt();
				athId[num].setathNum(id);
				
				System.out.print("Athletes name: ");
				name=DataIn.readLine();
				athId[num].setathName(name);
				
				System.out.print("Athletes age: ");
				age=DataIn.readLineInt();
				athId[num].setathAge(age);
				
				System.out.print("Event: ");
				event=DataIn.readLine();
				athId[num].setathEvent(event);
				
				
				System.out.print("Event time: ");
				time= DataIn.readDouble();
				athId[num].setathTime(time);
				
				//Check for next entry
				System.out.print("Do you wish to add another Record? y/n : ");
				rec = (char) System.in.read();
				if ( rec == 'n' || rec == 'N' )
      				{
         				done = true;
         				break;
   					}
         		else
					{
          				num = num + 1;
    					if (num > 11)
    						{
     							System.out.println ("Team is full");
     							return;
    						}
        			}
    	}
  	}<P>public static void Save(AthletesID[] athId)throws IOException
	{
  	//Initiate stream to save array to file
    FileOutputStream out=null;
   	PrintStream p;<P>    try
    	{
   			out=new FileOutputStream("a:events.dat");
			p=new PrintStream(out);
			
			for(int i=0;i<11;i++)
				{
					p.println(athId[i].getathNum());
					p.println(athId[i].getathName());
					p.println(athId[i].getathAge());
					p.println(athId[i].getathEvent());
					p.println(athId[i].getathTime());
				}
				p.close();
		}
					
		catch(IOException e)
			{
				System.err.println("File not opened"+e);
				System.exit(1);
			}
					
		finally
			{
				out.close();
			}
	}<P>
public static void exitProgram(AthletesID[] athId) throws IOException
	{
   	//Ask the user if they want to exit the program
    char ch;
    do
    	{
      		System.out.println("Press x to quit");
     		ch=(char)System.in.read();
    	}
    while (ch !='x');
      	System.out.println("Thankyou for using the Ned Kelly Athletics Team.");
     	System.exit(1);
  	}<P>public static int recExist(AthletesID[] athId) throws IOException
	{
   	//Check to see if the record exists
    int id;
    int rec=11;<P>    System.out.print("Please enter the ID number of the athlete. ");
    id=DataIn.readLineInt();<P>    for (int i=0;i<11;i++)
    	{
      		if ((athId[i].getathNum()==id) && (athId[i].getathNum()!=0))
      		rec=i;
      		break;
    	}
    	return rec;
  	}<P>public static int editEntry(AthletesID[] athId) throws IOException
	{
    //Declare variables
    int id, age;
    String name, event;
    double time;
    int rec=0;
    boolean done=true;<P>    //Ask for the ID number of the athlete to obtain record for editing
    while(done)
     	{
      		System.out.print("Please enter an athlete's number. ");
      		System.in.read(); System.in.read();
      		rec = DataIn.readLineInt();<P>      		if (rec != 0)
       		done = false;
     	}
        for(int i=0;i<11;i++)
        	{
      			if (athId[i].getathNum()==rec)
      				{  //Print out record
				        System.out.println("\tID number is " + athId[i].getathNum());
				        System.out.println("\tAthletes name is " + athId[i].getathName());
				        System.out.println("\tAthletes age is " + athId[i].getathAge());
				        System.out.println("\tEvent is " + athId[i].getathEvent());
				        System.out.println("\tEvent time is " + athId[i].getathTime());
				        System.out.println("\tPlease enter the new data. ");
				
				     	//Ask for new data for the record
				        System.out.print("Athletes ID: ");
				        id = DataIn.readLineInt();
				        athId[i].setathNum(id);
				
				        System.out.print("Athletes Name: ");
				        name = DataIn.readLine();
				        athId[i].setathName(name);
				
				        System.out.print("Athletes Age: ");
				        age = DataIn.readLineInt();
				        athId[i].setathAge(age);
				
				        System.out.print("Event: ");
				        event = DataIn.readLine();
				        athId[i].setathEvent(event);
				
				        System.out.print("Event Time: ");
				        time = DataIn.readLineDouble();
				        athId[i].setathTime(time);
      				}
     		}
			return rec;
    }
public static void displayData(AthletesID[] athId) throws IOException
 	{
    	int id=0, age=0;
    	String name=null, event=null;
    	double time=0;
  		boolean flag=true;
		char rec;
		int num, j=0;<P> 			//Get records to display
   			for (int i=0; i<11; i++)
   			{
				j++;<P>				num=j;
     				System.out.println("");
     				System.out.println("Record number:.. " + (i+1));
     				System.out.println("Athletes ID number is: " + athId[i].getathNum());
     				System.out.println("Athletes name is: " + athId[i].getathName());
     				System.out.println("Athletes age is: " + athId[i].getathAge());
     				System.out.println("Event is: " + athId[i].getathEvent());
     				System.out.println("Event time is: " + athId[i].getathTime());
     				System.out.println("");
					//Check for next entry
					System.out.print("Enter y/n for next record: ");
					rec = (char) System.in.read();
					if ( rec == 'n' || rec == 'N' )
      					{
         					flag = true;
         					break;
   						}
					else
         				{
          				num = num + 1;
    					if (num > 11)
    						{
     							System.out.println ("No more records");
     							return;
    						}
           			}
     				flag=false;
	 			}
   			System.in.read(); System.in.read();
   			if (flag)
   			{
    			System.out.println("");
    			System.out.println("No more Records..");
    			System.out.println("");
   			}
 	}
public static void deleteEntry(AthletesID[] athId)throws IOException
	{
   	int rec=0;<P>  	boolean done =false;
   	boolean flag =true;<P>   	while(flag)
   		{ //Ask for ID number of record
     		System.out.print("Enter Athletes ID number: ");
     		System.in.read(); System.in.read();
     		rec=DataIn.readLineInt();<P>     		if (rec !=0)
      		flag=false;
   		}
   		for (int i=0; i<11; i++)
   			{
     			if (athId[i].getathNum()==rec)
     				{ //Replace data with blanks
						athId[i].setathNum(0);
						athId[i].setathName(null);
						athId[i].setathAge(0);
						athId[i].setathEvent(null);
						athId[i].setathTime(0);
						System.out.println("");
						System.out.println("Record deleted: ");
						done=true;
      					return;
     				}
    		}
    		if(!done)
    			{
     				System.out.println("Record not found");
    			}
	}<P>}<P>

:confused:

[Edit: took out a massive quantity of spaces that was screwing up the post. -MrMills]

[This message was edited by MrMills on October 28, 2001 at 01:00.]
 
Your "snippet" of code is a tad long for most people to look over and find a problem with. How about I try to offer generic debugging tips instead?


  • Are arguments being passed in the right order?
  • Are variables initalized correctly?
  • Are the defaults correct?
  • Are there any sections of code that "work" that you can't explain?
  • Have manually stepped thru the code?
  • Where does the code being to function properly / improperly?
  • Write small test cases for sections of code to ensure they work properly
  • Comment out large hunks of code if need be to isolate the problem.


Sorry it's not a very polished list... anyone care to add or refine?

~Kevin
:)
 

NedKelly

Wise, Aged Ars Veteran
165
I had meant to put the NewMember method and some of the main in the question but I had some how copied the lot.
What was happening was when the program was running and you chose menu 1 it would just flick back to the menu and not go as it should, and display 'Athletes ID' waiting for a number input from the user that would then become the athletes number. It would then scroll through the list accepting input for name, age, event and time. This data was then stored in an array and would be saved by choosing menu 5. What I have since done is to change the num=num+1; to a for statement and it will now allow me to write the data in, but it always overwrites the first record and reads the file as having 11 records instead of the 7 that it does have. The other 4 records have been initialised as 0 for the ints, and the double, and null for the Strings.
So I still have some problems to deal with, and any help would be greatly appreciated.
Regards Ne :eek:
 

skriefal

Ars Scholae Palatinae
1,056
I just quickly glanced over your code, and will point out a few things that I noticed that look to be problems:

In the original version of the code you posted, it doesn't appear as though NewMember() would ever prevent you from adding at least one new member. Even it your data file already had 11 members, it'll still allow you to attempt to add a twelfth member. Of course the attempt would fail and an IndexOutOfBoundsException would be thrown by the VM.

Choosing option #1 from the main menu more than once in a single execution of the program appears to be problematic. Looks like the data entered after the first use of option #1 will be overwritten by the data entered after the second use of option #1.

I didn't actually compile this code and only spent a couple minutes glancing at it, so these obervations could be wrong. If these really are valid bugs, they should be fairly simple to fix.
 
Status
Not open for further replies.