0

I am developing a console application where I can register items. Each item has 3 properties serial number, model, year. I have 3 classes Laptop, Laptops(arraylist) and Office to run the application. So far I have managed to find the object itself by index number, but i need to list all objects with the property typed in.

This is how I ask user to choose the option

Laptops inHouse = new Laptops();
model = Console.askModel("Enter Model : ");
inHouse.findModel(model);
break;

That is the find method in Laptops class

public void findModel(String aModel)
{
    int arraySize = laptops.size();
    for(int i=0; i<arraySize; i++) {
        if (laptops.get(i).getModel() == aModel) {
            System.out.println(laptops.get(i));
        }
    }       
}

this is the askModel method in Console class.

public static String askModel(String aModel)
{
    System.out.println(aModel);
    String model = askString("Enter the model: ");
    return model;
}

Additionally, I am quite new to java, I understand the concept but still struggling on many thing so If I forgot to post a code which is needed to solve the problem I am sorry in advnace.

ssedano
  • 8,322
  • 9
  • 60
  • 98
Guns
  • 21
  • 3

2 Answers2

2

findModel is fine except for your String comparison which checks for object equality instead of String equality, change the comparison to:

if (laptops.get(i).getModel().equals(aModel))

For non-primitives, equality tests using == check if the object is literally identical (that it's the same instance), whereas String.equals will compare the actual String value.

Mark Elliot
  • 75,278
  • 22
  • 140
  • 160
0

You might want a HashMap instead of an ArrayList:

import java.util.HashMap

public class Laptops{
    Map<String, Laptop> laptops = new HashMap<String, Laptop>();
    //alternatively if java 7, do "= new HashMap<>();" instead

    public Laptop findModel(Laptop aModel){
        Laptop theModel = laptops.get(aModel);
        return theModel;
    }

To put the models in, you'll use the put method of HashMap:

public void addAModel(String modelName, Laptop aModel){

    laptops.put(modelName, aModel);
}

This way if you know a model's name (a String), it will return you the Laptop object you're after.

Ben
  • 1,759
  • 1
  • 19
  • 23