Level 2 Version B - Level 2 above plus
 Use of classes and objects to store and manipulate the item data

Example
• Write a new class ‘Event’ to represent details of sports event objects. A sports event consists of (for example) the event title, year and venue (“Olympic Games”, 2012, “London”)
• Your class definition should include an appropriate constructor method, and methods to allow addition, updating, searching and sorting of objects.
• The class should have a method to store all the objects from the array into a file. A further method should allow the contents of a previously stored file of objects to be restored into an array.
• Create a menu of options for the programme including
o Input a new object from a keyboard
o Search for an object and print details to screen
o Edit an object
o Sort the objects
o Print all the entries so far
o Save objects to a file
o Retrieve objects from a file
o Quit

//The main problem is with linear search and array created. I created array of objects, but i get int cannot be dreferenced. Also, problems with the array when storing..Always returns position 0

import javax.swing.JOptionPane;
import java.util.*;
import java.io.*;
class Event
{

	public static void main(String[] args)  throws IOException
	{
			final int ARRAYSIZE = 20; //larger array size.:P
			Sport[] sportEvent = new Sport[ARRAYSIZE];  //create object
				
    	
				int i =0;
				int a = 10;
	
				while (a!=0)
				{
		
				a= Integer.parseInt(JOptionPane.showInputDialog("Enter 1 to add\n" 
					+ "Enter 7 to update\n"
					+ "Enter 2 to save\n"
					+ "Enter 3 to search\n" 
					+ "Enter 4 to retrieve data\n"
					+ "Enter 5 to edit\n" 
					+ "Enter 6 to print\n"
					+ "Enter 0 to exit"));
			
					if(a==1)
			 		{
			 			add( i, sportEvent);
			 		} 
			 	
			 		if (a==2)
			 		{
			 			save(i, sportEvent);
				 	}	
				 	
				 	if (a==3)
			 		{
			 			search(sportEvent);
				 	}	
				 		
				 	if (a==4)
				 	{
				 		retrieve();
				 	}	
				 	
				 	if (a ==6)
				 	{
				 		print(i, sportEvent);
				 	}	
				 		
				 	if (a==7)
				 	{ 
				 		update(sportEvent);
				 	}
				}
	   
	}
	

	public static void add( int i ,Sport[] sportEvent)

	{
		i++;
			sportEvent[i] = new Sport();
			
	    	sportEvent[i].title = JOptionPane.showInputDialog("Enter the Title");
			sportEvent[i].year = Integer.parseInt(JOptionPane.showInputDialog("Enter the Year"));
			sportEvent[i].venue= JOptionPane.showInputDialog("Enter the Venue");
		
			sportEvent[i].printSport();
	
		
			
	}	
	
	public static void update(Sport [] SportEvent)
	{
		
	}
		
 
  	
	
	public static void search(Sport[] sportEvent)
	{
		String search = JOptionPane.showInputDialog("Enter the data you want to search");

		int result = linearSearch(sportEvent, search);
		
		if (result == -1)
			{
			JOptionPane.showMessageDialog(null, "Sorry " + search + " , not found");
			System.out.println("Sorry " + search + " , not found");
		
			}		
		
		else 
			{
			JOptionPane.showMessageDialog(null, "Search " + search + " found at position " + result); //position is always 0,when we run the program
			System.out.println("Search " + search + " found at position " + result);
			}
			
			
	}
	
	public static int linearSearch(Sport sportEvent[], String key )
	{
			
		for (int i =0; i< sportEvent.length; i++)
		{		
		if (sportEvent[i].getTitle.equals(key))	
	 	return i;
	 	
	 	
	 	if (sportEvent[i].getYear.equals(key))	//NullPointerException  or int cannot be derefrenced..
	 	return i; 
                if (sportEvent[i].getVenue.equals(key)) 
                return i;
	 
		}
		return (-1); //this doesnot work.
	}
	
	
	public static void edit (Sport sportEvent[])
	{
		
		
	}
	
	 public static void print(int i, Sport [] sportEvent)
  		{
  		for (i = 0; i<sportEvent.length; i ++)
		{
			System.out.println(sportEvent[i].getTitle());
                        

		}
  			
  			
  		}
  		

	

	public static void save(int i ,Sport sportEvent[]) throws IOException
		
	{
		
		String filename = JOptionPane.showInputDialog(" Enter to Create a filename" );
		final FileWriter outputSportFile = new FileWriter(filename);
		final BufferedWriter sportBuffer = new BufferedWriter(outputSportFile); 
		final PrintWriter sportPrint = new PrintWriter (sportBuffer);
		
	
		
			sportPrint.println(sportEvent[i].title);
			sportPrint.println(sportEvent[i].year);
			sportPrint.println(sportEvent[i].venue);
			
		sportPrint.close();
	
	i++	;
	}
	
	
	public static void retrieve() throws IOException
	{
		String filename = JOptionPane.showInputDialog("Enter the filename you wish to retrieve" );
		final FileReader inputSportFile = new FileReader(filename);
		final BufferedReader sportBuffer = new BufferedReader (inputSportFile);
		
		      String line1= sportBuffer.readLine();
     		  String line2= sportBuffer.readLine();
     		  String line3= sportBuffer.readLine();
			JOptionPane.showMessageDialog(null, line1 + line2 + line3);
			
			Sport x = new Sport();
			x.title = line1;
			x.year= Integer.parseInt(line2);
			x.venue= line3; 
			
		
			sportBuffer.close();
	}
	
}
import javax.swing. *;
class Sport

{
	public String title;  
	public int year;
	public String venue;  // object of type Sport consists of String title, int year and String venue, fields of 
			


	public Sport( String t, int y, String v) //initialise object parameters
	   {
	
		title = t; //stores 1st argumentpassed into title after new sport
		year = y; 
		venue= v;	
	   }
	   
	   public Sport() // if no arguments are passed, this will initialise default value  as " ", 0, "" 
	   {
	
		title = " ";
		year = 0;
		venue = " ";
	   }
	  
	 public String getTitle() 
	{
		return title;
	}

	 public int getYear()
	{
		return year;
	}
	
	 public String getVenue()
	{
		return venue;
	}
	
	
	 public void getTitle(String t) 
	{
		 title=t;
	}

	 public void getYear(int y)
	{
		year=y;
			
	}
	
	 public void getVenue(String v)
	{
		 venue=v;
	}
	  
	   
	   public void printSport()

	{
		System.out.println( "Title: " + title + "\n" + "Year: " + year +  "\n" + "Venue:" +venue);
	}
	
}

You have loops that look like this one:

for (i = 0; i<sportEvent.length; i ++)  {
  System.out.println(sportEvent[i].getTitle());

but there is no guarantee that the array is full of actual data, eg if you have an array of size 8, and have entered 6 records, the last two slots in the array will be empty and your attempts to retrieve data from them will fail.
Normal practice is to make the array "big enough" and have a separate variable that counts the inoputs and tells you how many elements of the array contain actual data.

You have loops that look like this one:

for (i = 0; i<sportEvent.length; i ++)  {
  System.out.println(sportEvent[i].getTitle());

but there is no guarantee that the array is full of actual data, eg if you have an array of size 8, and have entered 6 records, the last two slots in the array will be empty and your attempts to retrieve data from them will fail.
Normal practice is to make the array "big enough" and have a separate variable that counts the inoputs and tells you how many elements of the array contain actual data.

Double post? Oh well.

ps: Your setX methods are all called getX - very confusing.

Oh its setx method. Sorry i am just playing around with the objects of field too much.
my main problem is still .int year is seen as integer and not object , so i tried to initialise and all different things in CLASS Sport.

Yeah i dont know..I have been trying all very different things. Linear search just dont work..and i think i have problem with array storing datas...it's almost like it only stores in one position and always in 0..and not 0,1,2,3,4,5,6,7,8

pardon my english. thankx for your help .really appreciated.

if (sportEvent.getYear.equals(key))
where getYear returns an int, and Key is a String
won't work because
a) an int is never equal to a String
b) ints are primitives, not classes, and have no methods. sportEvent.getYear returns an int, but then you try to call .equals(..) on that.

One possible thing to think about is a polymorphic search method with 2 variants- one taking a String as key (searching name & venue only, the other taking an int as Key, and searching only to year.

If you fix that problem I think your search will work.

As for adding - one thing is that you increment i before adding the new record, so the first record goes into array[1] and array[0] is left empty, ready to give you null pointers etc when you try to access it. And i is a really unhelpful name for that variable!

There are lots of other things that can be improved, but that should do for now.

Thanks for your reply, sir.

YEah i have been jus playing so much with this...I think i have mistakenly put wrong code in linear search up..its like this..as for now..

for (int i =0; i< sportEvent.length; i++)
		{		
		if (sportEvent[i].getTitle().equals(key))	
	 	return i;
	 	
	    if (sportEvent[i].getYear()==(key))       //shall i just do it like this..coz i thought as i was creating an object and int within that that object ..(.equal) should work... And i get *incomparable types: int and java.lang.String*
        return i;
	 	if (sportEvent[i].getVenue().equals(key))	
	 	return i;

I think i need a for loop for array..but i m not sure either..just too many things in my head.

also So do you think

if (sportEvent[i].getVenue().equals(key))  //does get method has advantage?	
	 	return i;
this is much better than just 
if (sportEvent[i].venue.equals(key))	
	 	return i;

i even tried .toString() ...it just doesnot work..I have just been playing around with this for so many hours now...
Also i++ ..I had that at end..lol..i was just playing around with it too..:P.THANKS.

1. If you really insist on trying to compare an int and a String then your best option is to convert the int to a String, then compare that with the key. One of the toString methods in the Integer class will do the conversion for you (I'll leave you to find out which).

sportEvent.getVenue() vs sportEvent.venue
This is almost a religious question and people can get quite heated about it. My own opinion is that exposing a classes instance variables is asking for trouble - sooner or later another method in another class on another thread will do something unexpected with one of those vars and the debugging will be horrible. Forcing people to use get/set keeps you in control.

I am still having troubles with arrays.
It only shows the last value and position is always 0.

import javax.swing.JOptionPane;
import java.util.*;
import java.io.*;
class Event
{

	public static void main(String[] args)  throws IOException
	{	
			int i;
			final int ARRAYSIZE = 20;
			Sport[] sportEvent = new Sport[ARRAYSIZE];  //create object
				
    		for (i = 0; i <sportEvent.length; i++) // input details of 3 roads
       	           {
                   sportEvent[i] = new Sport();   
        	   }   //I dont know why but this for loop helped solving my linear search ..returns the value.. but int couldnot be defrenced...so i just left it..however..i gotto get my array working 1st.

				
				int a = 10;
	
				while (a!=0)
				{
		
				a= Integer.parseInt(JOptionPane.showInputDialog("Enter 1 to add\n" 
					+ "Enter 7 to update\n"
					+ "Enter 2 to save\n"
					+ "Enter 3 to search\n" 
					+ "Enter 4 to retrieve data\n"
					+ "Enter 5 to edit\n" 
					+ "Enter 6 to print\n"
					+ "Enter 0 to exit"));
			
					if(a==1)
			 		{
			 			add(i, sportEvent);
			 		} 
			 	
			 		if (a==2)
			 		{
			 			save(i, sportEvent);
				 	}	
				 	
				 	if (a==3)
			 		{
			 			search(sportEvent);
				 	}	
				 		
				 	if (a==4)
				 	{
				 		retrieve();
				 	}	
				 	
				 	if (a ==6)
				 	{
				 		print(sportEvent);
				 	}	
				 		
				 	if (a==7)
				 	{ 
				 		//update(sportEvent);
				 	}
				}
	   
	}
	
//
	public static void add( int i, Sport[] sportEvent)

	{	
		i=0;
		
				
			//Scanner keyboard = new Scanner(System.in);
		
			
	    	sportEvent[i].title = JOptionPane.showInputDialog("Enter the Title");
			sportEvent[i].year = Integer.parseInt(JOptionPane.showInputDialog("Enter the Year"));
//			String string = sportEvent[i].year.nextInt(); ignore dis for now
			sportEvent[i].venue= JOptionPane.showInputDialog("Enter the Venue");
		
			
		i++;

//DO i need a for loop maybe...
			
	}

Line 15 - yes, when you declare a new array of Sports the array is empty - it just contains slots that you can put Sports in. If you try to access an empty slot you get a null pointer Exception. Your loop at line 15 puts a new Sport object into each of those slots, so now they all have something valid in them.

Line 70 - you set i back to zero every time you go thru the loop, so every entry just goes into [0]

Line 16 - end the for loop, so the following code is now outside the loop and only gets executed once. The } probably needs to be about line 63.
This would have been more obvious if your indentation was correct - it currently shows how you think the code should be, not how it actually is.
If you're not currently using a tool that indents code for you, then I recommend you start now, and keep the indentation updated.

Thanks to the reply sir. Firstly, thanks a lot for reminding me about indentation.
Secondly, if my for loop will end at line 63 , I cant exit my menu because it will keep going on lopp.
Thirdly, I see the problem with i being the 0. Thats why it was 0. But, when i removed that.."main" java.lang.ArrayIndexOutOfBoundsException: 20 ..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.