如何将一个字符串与多个字符串数组进行比较
How to compare a string to multiple string arrays
我正在尝试编写一个程序,用户在其中输入他们的购物清单,然后根据项目的类型,程序会给你一个很好的订单来购买你的项目(即把肉放在一起,然后蔬菜一起)
这是我当前的问题,我无法让用户输入与我拥有的商店商品的多个字符串类型数组进行比较。
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");
}
}
您无需执行循环,因为 contains 方法将与列表中的所有元素进行比较。
我 运行 你的代码和下面的代码工作正常。
如果(Arrays.asList(VegiFruit)。包含(InptOne))
{
System.out.println("Item is a VEGI "+InptOne);
}
if(Arrays.asList(Meats).contains(InptOne))
{
System.out.println("Item is a MEAT "+InptOne);
}
但是,请注意,这是区分大小写的比较,如果用户没有以您的格式输入蔬菜,那么它将不起作用。
要解决该问题,您可以采用两种方法:
- 在大写字母中包含 veegetables/meat 的列表,并在包含方法中进行比较之前制作 input.toUpperCase()。
2.Use Array contains() without case sensitive lookup?
上的答案
我正在尝试编写一个程序,用户在其中输入他们的购物清单,然后根据项目的类型,程序会给你一个很好的订单来购买你的项目(即把肉放在一起,然后蔬菜一起) 这是我当前的问题,我无法让用户输入与我拥有的商店商品的多个字符串类型数组进行比较。
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");
}
}
您无需执行循环,因为 contains 方法将与列表中的所有元素进行比较。
我 运行 你的代码和下面的代码工作正常。 如果(Arrays.asList(VegiFruit)。包含(InptOne)) { System.out.println("Item is a VEGI "+InptOne); }
if(Arrays.asList(Meats).contains(InptOne))
{
System.out.println("Item is a MEAT "+InptOne);
}
但是,请注意,这是区分大小写的比较,如果用户没有以您的格式输入蔬菜,那么它将不起作用。
要解决该问题,您可以采用两种方法:
- 在大写字母中包含 veegetables/meat 的列表,并在包含方法中进行比较之前制作 input.toUpperCase()。
2.Use Array contains() without case sensitive lookup?
上的答案