0

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.");
        }
    }
}
3
  • 1
    Outside of your loop - create a variable of type Laptop and set it to null. Within the loop, if you find a match, assign it to the variable. After the loop, check if the variable is null - if so, print "Invalid ID" otherwise print the laptop details from the variable. Does this help? Commented Jan 23, 2020 at 4:57
  • @RiaanNel This helps immensely. I think this is the route I will use to achieve what I want. I was struggling with it and you presented it in a way that was super easy to understand while still leaving it up to me to implement. Cannot thank you enough. Commented Jan 23, 2020 at 5:03
  • 1
    You can break from the loop using break keyword if there is a match . Also have a variable outside the loop that stores the matched laptop. Move sop outside the loop. Commented Jan 23, 2020 at 5:15

3 Answers 3

2

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.");
    }
Sign up to request clarification or add additional context in comments.

Comments

1

You can do this using a return statement that is used after printing a match

for(int i=0; i<arr.size(); i++) {

    //If entered ID matches, print laptop information.
    if(inputId == (arr.get(i)).getId()) {
        System.out.println((arr.get(i)).getModel() + " CPU: " + (arr.get(i)).getCpu() + " GPU: " +
                (arr.get(i)).getGpu() + " Memory: " + (arr.get(i)).getMemory() + "GB ID: " + 
                (arr.get(i)).getId());

        return;
     }
}

 // outside loop
 System.out.println("Invalid ID.");

edit

If you have you ArrayList set up properly as ArrayList<Laptop> then you would not need all those crazy casts.

edit2

If you a foreach loop it would be even cleaner

for (Laptop lt : arr) {
    if (iputId == lt.getId()) // etc

7 Comments

Correct me if I'm wrong, but wouldn't this print "Invalid ID." every time the method is called on regardless of if there was a match or not? Also, I can tell my ArrayList<Laptop> to print and it will just fine, but it'll print how they typically print (with the arraylist name then inside brackets the name of each parameter set equal to their value), and this doesn't match the required format I need.
No, because you are returning from this method after printing the match
Got it. Thank you, your solution most definitely would work!
@BrandonBischoff wrote Also, I can tell my ArrayList<Laptop> to print and it will just fine, but it'll print how they typically print (with the arraylist name then inside brackets the name of each parameter set equal to their value), and this doesn't match the required format I need - please re-read what I posted. I am not telling you to use ArrayList<Laptop> to change the printing.
Change your method to private static void findLaptop(ArrayList<Laptop> arr) and then you do not need to cast, and makes the method type-safe
|
1

Supposing you have a class called Laptop as follows:

public class Laptop {

    private String id;
    private String manufacturer;
    // other fields

    // getters and setters
}

You can find matches with an id using Java 8 Streams:

List<Laptop> laptops = ...
String idToSearch = "something";

Optional<Laptop> result = laptops.stream()  // convert into stream for easier handling
    .filter(l -> l.getId().equals(idToSearch))  // find only laptops with a matching id
    .findFirst();  // find the first one, if present

The variable result is an Optional<Laptop>, meaning it may or may not contain a Laptop value. You can consume this result as follows:

Laptop laptop = result.get();  // throws an exception if no value present, not reccomended

Laptop laptop = result.orElse(null);  // returns null if no value present

result.ifPresent(laptop -> {
    doSomething(laptop);  // this function is only called if a value is present
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.