Results 1 to 4 of 4
  1. #1
    coasterguy10 is offline Member
    Join Date
    Sep 2011
    Posts
    21
    Rep Power
    0

    Post Problem with my equals method

    I am having a problem with comparing objects in my code. The method is supposed to compare certain aspects of a Car or SoldCar object and return whether or not they are similar cars (the method would return true). I have designed the loop in main so that a car does not compare itself, but when I run the loop, nothing is printed, indicating no similar cars were found, but there should be at least two cars that are found to be similar so their ID numbers should be printed. I don't know if its a problem with the way I have written my isEqual method, or if it is the way I have written the loop in main. The loop to compare the cars starts at line 116. If someone could take a look at the loop and the methods I have written I would greatly appreciate it.

    Java Code:
       import java.util.ArrayList;
       import java.io.FileReader;
       import java.io.BufferedReader;
       import java.io.FileNotFoundException;
       import java.io.IOException;
    
       public class SellingCars
       {
          public static void main(String[] args)
          {
             String type;
             int id, modelYear;
             double dealerCost;
             double priceSold;
             Date dateArrived, dateSold;
             String customer;
             String makeMod;
             boolean equal;
             ArrayList<Car> cars = new ArrayList<Car>();
              
             FileReader reader=null;
             Car car;
             SoldCar sCar;
          
             String temp="";
             
             try
             {
                reader = new FileReader("cars.txt");
                BufferedReader in = new BufferedReader(reader);
                
                while ((temp = in.readLine()) != null)
                {        
                   equal = false;          
                   String[] data = temp.split(" ");
                   if (data[0].equals("X"))
                   {
                      break;
                   }
                   else if (data[0].equals("C"))
                   {
                      dealerCost = Double.parseDouble(data[1]);
                      id = Integer.parseInt(data[2]);
                      dateArrived = new Date(data[3], Integer.parseInt(data[4])
                         							, Integer.parseInt(data[5]));
                      modelYear = Integer.parseInt(data[6]);
                      makeMod = data[7];
                      car = new Car(dealerCost, id, dateArrived, modelYear, makeMod);
                      for(int i = 0; i < cars.size(); i++)
                      {
                         if(car.getIdNumber()==cars.get(i).getIdNumber())
                         {	
                            System.out.println("Error, ID "+car.getIdNumber()+" already in list"
                               					+", car not added");
                            equal=true;
                         }
                      }
                      if (!equal)
                         cars.add(car);
                   }
                   else if (data[0].equals("S1"))
                   {
                      id = Integer.parseInt(data[1]);
                      priceSold = Double.parseDouble(data[2]);
                      customer = data[3];
                      dateSold = new Date(data[4], Integer.parseInt(data[5])
                         							, Integer.parseInt(data[6]));
                      sCar = new SoldCar(id, priceSold, customer, dateSold);
                      for(int i = 0; i < cars.size(); i++)
                      {
                         if(sCar.getIdNumber()==cars.get(i).getIdNumber())
                         {	
                            System.out.println("Error, ID "+sCar.getIdNumber()+" already in list"
                               					+", car not added");
                            equal=true;
                         }
                      }
                      if (!equal)
                         cars.add(sCar);
                   }
                   else
                   {
                      dealerCost = Double.parseDouble(data[1]);
                      id = Integer.parseInt(data[2]);
                      dateArrived = new Date(data[3], Integer.parseInt(data[4])
                         							, Integer.parseInt(data[5]));
                      modelYear = Integer.parseInt(data[6]);
                      makeMod = data[7];
                      priceSold = Double.parseDouble(data[8]);
                      customer = data[9];
                      dateSold = new Date(data[10], Integer.parseInt(data[11])
                         							, Integer.parseInt(data[12]));
                      sCar = new SoldCar(dealerCost, id, dateArrived, modelYear, makeMod,
                         					priceSold, customer, dateSold);
                      for(int i = 0; i < cars.size(); i++)
                      {
                         if(sCar.getIdNumber()==cars.get(i).getIdNumber())
                         {	
                            System.out.println("Error, ID "+sCar.getIdNumber()+" already in list"
                               					+", car not added");
                            equal=true;
                         }
                      }
                      if (!equal)
                         cars.add(sCar);
                   }
                   
                   temp = in.readLine();
                }
             
             }
                catch (IOException ioe)
                {
                   ioe.printStackTrace();
                }     
             for(int i = 0; i < cars.size(); i++) // Loop that will compare cars and return their ID numbers if they are similar
             {	
                for(int j = i+1; j < cars.size();j++)
                {
                   if(cars.get(i).isEqual(cars.get(j)))
                      System.out.println("Cars "+cars.get(i).getIdNumber()
                         				+" and "+cars.get(j).getIdNumber()
                         				+" are similar");
                }
             }
             for(int i = 0; i < cars.size(); i++)
                System.out.println(cars.get(i));
          }
       }
    
    //isEqual method from my Car class
    public boolean isEqual(Car other)
    	{
    		return modelYear==other.modelYear 
    				 && dateArrived.equals(other.dateArrived)
    				 && makeModel.equals(other.makeModel);
    	}
    
    //isEqual method from my SoldCar class
    public boolean isEqual(SoldCar other)
    	{
    		return super.isEqual(other)&& dateSold.equals(other.dateSold);
    	}

  2. #2
    pbrockway2 is online now Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,574
    Rep Power
    12

    Default Re: Problem with my equals method

    I can't see anything amiss - but that might just be me and, bear in mind, we can only see bits of the program.

    I don't know if its a problem with the way I have written my isEqual method, or if it is the way I have written the loop in main.
    There's a third possibility: the data may not be what you think it is. We need to disentangle these possibilities.

    (A) Write a small program that thoroughly tests the isEqual() methods. Ie, it creates cars by hand, compares them, and prints the result which you check against what you were expecting. Try lots of examples including comparing sold cards with unsold ones to make sure these methods are doing exactly what you expect. The idea is to convince yourself that the comparison is being made correctly.

    (As a general point, such test programs are needed for everything! And the time to write them is when - some would say *before* - you write a method for one of the car types.)

    (B) Next look at main(). It's doing too much. When a method does lots of things there are lots of things it could be doing wrong. Break this method up: one thing that occurs to me is that it does a similar thing three times. Perhaps there could be a "helper" method (or even a separate class) that creates a car based on a line of text. Such things are called "factory" methods or classes.

    One simple version of this would be to have a method in each of the car types that creates a car based on a line of text (or throws an exception if anything goes wrong). There might even be two such methods for the sold cars. In that case all main() has to do is read the start of the line and then pass the line to the appropriate method to get the car to add to the array (after checking the id). The idea is to move a lot of the variables (type, modelYear etc) out of main() whose job reduces that of reading the file and populating an array with cars whose ids have been checked for duplicates.

    Again check. Which you are doing in this case by printing all the cars at the end of main(). You don't say, but is this printing what you expect? Ie have all and only the cars you expect ended up in the array list?

    (C) Data files can go wrong in lots of ways. (Including containing invisible text - whitespace - like tabs). Perhaps you need to alter the equals() methods so that you can see exactly what is going on:

    Java Code:
    public boolean isEqual(Car other)
        {
            boolean result = modelYear==other.modelYear 
                     && dateArrived.equals(other.dateArrived)
                     && makeModel.equals(other.makeModel);
            System.out.println("Comparing: " + this);
            System.out.println("     with: " + other);
            System.out.println("   result: " + result);
            return result;
        }
    You are going to get a lot of output so consider testing with a small data file.

    You claim that there should be a pair with isEqual() being true. You should now be able to see that pair being compared.

  3. #3
    Solarsonic is offline Senior Member
    Join Date
    Mar 2011
    Posts
    261
    Rep Power
    4

    Default Re: Problem with my equals method

    You're confusing class variables and local variables, and you clearly don't understand object-oriented programming.

    Instead of using variables defined in this handler class, try changing your isEqual() method to

    Java Code:
    public boolean isEqual(Car car1, Car car2)
    And compare two Car objects. Something like this:

    Java Code:
    public boolean isEqual(Car car1, Car car2)
        {
            return car1.getModelYear()==car2.getModelYear()
                     && car1.getDateArrived().equals(car2.getDateArrived())
                     && car1.getMakeModel().equals(car2.getMakeModel());
        }
    And your Car class will have some methods like this:

    Java Code:
    public int getModelYear() {
    return modelYear;
    }
    public String getDateArrived() {
    return dateArrived;
    }
    etc. That's object-oriented programming.

  4. #4
    coasterguy10 is offline Member
    Join Date
    Sep 2011
    Posts
    21
    Rep Power
    0

    Default Re: Problem with my equals method

    pbrockway2, I did what you suggested and tested the isEqual method with a smaller array and it worked fine. I also emailed my professor about the problem I was having and he sent back an email with output that differed from mine very much. I just now remembered that for some reason, when my program was reading in the lines from my text file, it was skipping over every other line (or it appeared to be from the output) and so I entered an extra line of space between each set of data which solved my problem of the program only outputting every other line of text that was good. Can you or Solarsonic or anyone else see why my program would do this?

Similar Threads

  1. What is the use of equals () method?
    By srinivasmallabathula in forum Advanced Java
    Replies: 3
    Last Post: 08-04-2011, 06:57 PM
  2. equals method :::::HELP:::::
    By alihht in forum New To Java
    Replies: 5
    Last Post: 03-09-2010, 08:19 AM
  3. ArrayLists compareTo method, equals method
    By random0munky in forum New To Java
    Replies: 2
    Last Post: 10-26-2009, 08:20 PM
  4. equals method
    By mani_miit in forum Advanced Java
    Replies: 7
    Last Post: 09-09-2009, 11:26 PM
  5. equals method
    By timkd127 in forum New To Java
    Replies: 2
    Last Post: 01-24-2009, 07:52 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •