-6

I have an object called Product and I want to check if a user-entered string matches the name of one of the Products.

I tried the code below but it doesn't work.

Product  laptop = new Product(1, "Laptop", "Type", 1350.25, "black");
Product  mouse = new Product(2, "Mouse", "Type", 50.50, "black");

String check = new String("laptop");

if (check.equals(instanceof Product))  
{
    System.out.println("Yes it is.");
}
    else
{
    System.out.println("No, it is not.");
}
Neuron
  • 5,141
  • 5
  • 38
  • 59
John R.
  • 420
  • 4
  • 14
  • 5
    That's wrong on so many levels. What do you want help with. – Shanu Gupta Jun 03 '18 at 10:37
  • The purpose of `instanceOf` is to check if a instance is of a specified class. – Jens Jun 03 '18 at 10:37
  • 1
    Create a collection of all `Product` instances, iterate over that and for each element check wether or not the `name` (or whatever) contains the search term. – luk2302 Jun 03 '18 at 10:38
  • 1
    Your examples show that you lack the fundamentals or programming. I would recommend you find a good tutorial which comes with homework examples and work through that tutorial (while completing **every** example faithfully). – Neuron Jun 03 '18 at 12:49

1 Answers1

0

I assume you have a name variable in your Product class. So what you would want to do is compare the name variable to the String. Something like this:

private String name;
Product  laptop = new Product(1, "Laptop", "Type", 1350.25, "black");
Product  mouse = new Product(2, "Mouse", "Type", 50.50, "black");

String check = new String("laptop");
if(check.equals(laptop.getName()) {
    System.out.println("Match!");
} else {
    System.out.println("No match...");
}

Here's a good SO discussion about the proper use of instanceof:

What is the 'instanceof' operator used for in Java?

GBlodgett
  • 12,704
  • 4
  • 31
  • 45