【问题标题】:How to compare a string to multiple string arrays如何将一个字符串与多个字符串数组进行比较
【发布时间】:2015-09-13 01:40:20
【问题描述】:

我正在尝试编写一个程序,在该程序中,用户输入他们的购物清单,然后根据商品的类型,程序会给你一个很好的订单来购买你的商品(即把肉和蔬菜放在一起一起) 这是我当前的问题,我无法让用户输入与我拥有的多个字符串类型数组进行比较。

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");
    }
}

【问题讨论】:

  • ip的目的是什么?
  • 请告诉我们具体的行为是什么。您输入的是什么输入,程序的行为是什么?尽管您正在使用一些循环,其唯一效果似乎是浪费时间,但 contains 方法似乎使用正确。在您告诉我们的地方发布问题通常没有帮助,基本上,“它工作不正常”。你有更多的信息,请不要对我们保密。

标签: java arrays string logic


【解决方案1】:

您无需遍历循环,因为 contains 方法将与列表中的所有元素进行比较。

我运行了您的代码,下面的代码运行良好。 if(Arrays.asList(VegiFruit).contains(InptOne)) { System.out.println("项目是一个 VEGI "+InptOne); }

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

但是,请注意,这是区分大小写的比较,如果用户没有按照您的格式输入蔬菜,那么它将不起作用。

要解决这个问题,您可以采取两种方法:

  1. 将蔬菜/肉类列表放在大写字母中,并在包含方法中进行比较之前创建 input.toUpperCase()。

2.使用Array contains() without case sensitive lookup?上的答案

【讨论】:

  • 好的,非常感谢,我对此很陌生,不知道我可以摆脱 for 循环
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-04
相关资源
最近更新 更多