在数组列表中搜索特定的文本字符串

时间:2014-06-12 05:10:33

标签: java arrays string arraylist

如何在数组列表中查找单词?在我的代码中,我使用get按位置搜索数组,但我想比较一个字符串(来自用户输入)和数组的元素,然后如果找到它,则打印包含在找到字符串的位置中的所有元素。

import java.util.ArrayList;import java.util.Scanner;


public class Shoes {
Scanner input = new Scanner(System.in);
ArrayList shoesList = new ArrayList();



public void Shoe1() {

    int Shoe1;
    String Color1;
    float Size1;
    float Price1;


    System.out.println("Enter model of the shoe: ");
    Shoe1 = input.nextInt();
    System.out.println("Enter color of the shoe: ");
    Color1 = input.next();
    System.out.println("Enter size of the shoe: ");
    Size1 = input.nextFloat();
    System.out.println("Enter price of the shoe: ");
    Price1 = input.nextFloat();

    shoesList.add("" + "model: " + Shoe1 + "\n" + "color: " + Color1 +//adds the variables, shoe, color, size and 
            "\n" + "size: " + Size1 + "\n" +"price: " + Price1);        //price to one spot of the array
}



 public void getSpecific(int value){
     //gets and specific value taking input from the user
    int select = value;
    System.out.println(shoesList.get(select));



    }

所以我想做的是搜索鞋子的模型,说我有一个模型1,如果我搜索“模型1”我希望程序显示存储在数组位置的所有信息模型1是。

3 个答案:

答案 0 :(得分:0)

您有List StringstartsWith(String)contains(CharSequence)。但是,您应该将这些字段移到Shoes类中,并在Shoes中存储List的实例。

答案 1 :(得分:0)

没问题! 所以,我们想:

1. Loop over the shoeList
2. See which shoe has the text
3. Print that shoe

//Note: Instead of taking an int, its better to take all the String. Example "model 1".

public void printShoe(String value){
for(String shoe : shoeList){ //The sign ":" said that, for every String in shoeList, 
                             //do the following

    if(shoe.contains(value))
       {System.out.println(shoe);break;}//Break will make it not print more than 1 shoe


   }

}

答案 2 :(得分:0)

这种方法可以做到。

String getIfContainsUserInput(String userInputString) 
{
     for (String shoeString : shoesList) 
     {
         if (shoeString.matches(".*" + Pattern.quote(userInputString) + ".*"))
           return shoeString;
    }

  return null;
}