处理/ Java:来自一个arraylist

时间:2017-01-06 15:01:03

标签: java arraylist output processing

我想有两个输出,就像我输入" ora",我希望它输出" orange"和"橙汁",两个字符串,但你会怎么做?

class searcher {
      ArrayList<String> toBecompared= new ArrayList<String>(Arrays.asList("orange", "orange juice", "apples", "cola", "soda"));
      void search() {
        String[] words = {text}; 
        // text is a user input
        // for loop test for if the "list" contains "text" (user input)
        for (int i = 0; i < toBecompared.size(); i++) {
          for (int w = 0; w < text.length(); w++) {
            try { 
              if (toBecompared.get(i).contains(words[w])) {
                println(words[w] +"  " + toBecompared.get(i));
              }
            }
            catch(Exception a) {
            }
          }
        }
      }
    }

1 个答案:

答案 0 :(得分:0)

我找到了一种方法,但我不确定它是否是最佳方式:P

class searcher {
  ArrayList<String> toBecompared= new ArrayList<String>(Arrays.asList("orange", "orange_juice", "apples", "cola", "soda"));
  String comparing ="orange orange_juice apples cola soda";
  String[] splited = comparing.split("\\s+");
  String compared1;
  String compared2;

  boolean True = false;

  void search() {
    String[] words = {text}; // text is a user input
    for (int i = 0; i < toBecompared.size(); i++) {
      for (int w = 0; w < text.length(); w++) {
        try { 
          if (toBecompared.get(i).contains(words[w])) {
            //println(words[w] +"  " + toBecompared.get(i));

            if (True == true) {
              compared2 = splited[i];
              True = false;
            } else {
              compared1 = splited[i];
              True = true;
            }
          }
          println(compared1);
          println(" ");
          println(compared2);
        }

        catch(Exception a) {
        }
      }
    }
  }
}