-2

I'm trying to write a program in which the user inputs their grocery list then based upon the type of item it is the program will give you a good order to shop for your items(i.e puts the meats together and the vegetables together) here's my current problem, I can't get the user input to compare to the multiple string type arrays I have of store items.

String[] VegiFruit = {"Apples", "Lettuce", "Broccoli"};
String[] Meats = {"Ground beef", "Hambuger"};

Scanner USER_IN = new Scanner(System.in);
Methods Use = new Methods(); //This is another class I have, it just makes printing empty lines and lines  of **** look nicer

Use.border();
System.out.println("Enter Item name then follow instructions.");
Use.space();

System.out.print("Item 1: ");
String InptOne = USER_IN.nextLine();

}
for (int i = 0; i < VegiFruit.length; i++)
{
    if(Arrays.asList(VegiFruit).contains(InptOne))
    {
        System.out.println("Item is a VEGI");
    }
}
for(int p = 0; p < Meats.length; p++)
{
    if(Arrays.asList(Meats).contains(InptOne))
    {
       System.out.println("Item is a MEAT");
    }
}
theB
  • 6,450
  • 1
  • 28
  • 38
N.LeFevre
  • 19
  • 6
  • What is the purpose of `i` and `p`? – ajb Sep 13 '15 at 01:43
  • 3
    Please tell us what the exact behavior is. What input are you typing in, and what is the program's behavior? Although you're using some loops whose only effect appears to be to waste time, the `contains` method seems to be used correctly. It's generally not helpful to post questions where you tell us, basically, "it isn't working right". You have more information than that, please don't keep it a secret from us. – ajb Sep 13 '15 at 01:46

1 Answers1

0

you need not go through the loops as contains method will compare with all the elements in the list.

I ran your code and the below works fine. if(Arrays.asList(VegiFruit).contains(InptOne)) { System.out.println("Item is a VEGI "+InptOne); }

        if(Arrays.asList(Meats).contains(InptOne))
        {
           System.out.println("Item is a MEAT "+InptOne);
        }

However, please note that this is case senstive comparison and if the user does not enter the vegetable in your format then it will not work.

To solve that problem, you can take 2 approaches:

  1. Have the list of veegetables/meat in caps and make the input.toUpperCase() before comparing it in contain method.

2.Use the answer on Array contains() without case sensitive lookup?

Community
  • 1
  • 1
Smiles
  • 46
  • 8