2014-06-12 4 views
0

как я могу найти слово в списке массивов? в моем коде я ищу массив по позиции с помощью 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

У вас есть List из String Вы можете использовать либо startsWith(String), либо contains(CharSequence). Однако вы должны перенести эти поля в свой класс Shoes и хранить экземпляры Shoes в своем List.

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 


    } 

} 
+0

спасибо, я ценю ваши ответы я хочу попробовать это. – user3732562

0

Этот метод будет делать это.

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

    return null; 
} 
+0

Использование сопоставления шаблонов слишком сложно. String.contains ("...") - это путь. – MichaelS

Смежные вопросы