Search code examples
javaloopsarraylistmethodsuser-input

Java Method to find a match in ArrayList


I have the following method in a program of mine that allows a user to enter a unique ID that is associated with a laptop in an ArrayList.

The desired output is as follows:

  • If the ID entered by the user matches an ID in the ArrayList, the laptop and its specifications will print out.
  • If the ID does not match, it will print out "Invalid ID".

I am very close to achieving this; however I can only figure out how to get it to print whether or not it matches for each laptop in the list. So for example, if the ID entered by the user matches one of three laptops in the list it will print as follows:

Acer Predator Helios 300 CPU: Intel i7-9750h GPU: NVIDIA GTX1660ti Memory: 16GB ID: 1234567

Invalid ID.

Invalid ID.

So my question is: how do I get it to print ONLY the single match or "Invalid ID" while still being able to loop through the entire list to check for a match? Not necessarily asking you to spoon feed me the fix, but at least help point me in the right direction or help with the logic. I thank you in advance for any help!

My method is as follows:

private static void findLaptop(ArrayList arr) {

    //Prompt user to input an ID.
    System.out.println("Input ID: ");
    System.out.println();

    //Scan for user input.
    Scanner keyboard = new Scanner(System.in);
    int inputId = keyboard.nextInt();

    //Loop through ArrayList and check for a match.
    for(int i=0; i<arr.size(); i++) {

        //If entered ID matches, print laptop information.
        if(inputId == ((Laptops) arr.get(i)).getId()) {
            System.out.println(((Laptops)arr.get(i)).getModel() + " CPU: " + ((Laptops)arr.get(i)).getCpu() + " GPU: " +
                    ((Laptops)arr.get(i)).getGpu() + " Memory: " + ((Laptops)arr.get(i)).getMemory() + "GB ID: " + 
                    ((Laptops)arr.get(i)).getId());
        }
        //If entered ID does not match, print invalid ID.
        else if(inputId != ((Laptops) arr.get(i)).getId()) {
            System.out.println("Invalid ID.");
        }
    }
}

Solution

  • Use below code:

        //Create a boolean
        boolean found= false; 
        for(int i=0; i<arr.size(); i++) {
            //If entered ID matches, print laptop information.
            if(inputId == ((Laptops) arr.get(i)).getId()) {
                System.out.println(((Laptops)arr.get(i)).getModel() + " CPU: " + ((Laptops)arr.get(i)).getCpu() + " GPU: " +
                        ((Laptops)arr.get(i)).getGpu() + " Memory: " + ((Laptops)arr.get(i)).getMemory() + "GB ID: " + 
                        ((Laptops)arr.get(i)).getId());
                        //set boolean true and break
                        found = true;
                        break;
            }
        }
      //Out side the look check If entered ID does not match, print invalid ID.
        if(!found) {
           System.out.println("Invalid ID.");
        }