2015-01-31 66 views
-4
System.out.println("What animal are you looking for?"); 
String find=input.nextLine(); 
for(int i=0; i<array.size(); i++) 
{ 
    if(array.get(i).equals(find)) 
    { 
     System.out.println(array.get(i)+" is in the ArrayList"); 
    } 
} 


它不返回任何内容。你认为代码有什么错误? (它应该从用户采取串并设法找到它在ArrayList中。)搜索ArrayList中的字符串

+0

有什么列表的内容? – 2015-01-31 18:01:19

+0

['List.contains'](http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html#contains(java.lang.Object))?你的'阵列'是什么? – 2015-01-31 18:02:33

+0

请发布完整的代码。它会帮助我们! – CodeWalker 2015-01-31 18:03:37

回答

1

有对println语句被跳过两个可能的原因:

  • ArrayList是空
  • ArrayList不为空,但不包含搜索到的单词。

只要尝试调试你的代码,你会很快找到原因。

1

尝试没有循环

if (array.contains(find)) { 
    System.out.println(find + " is in the ArrayList"); 
} 

但你的代码看起来确定,所以它是最有可能的是你搞砸了在代码中的东西,你不要在这里分享。

+0

我认为他的意思是“把它放在for循环中” – JClassic 2015-01-31 18:13:43

+0

@kocko是的,你是对的 - 已经修复了。 – damienix 2015-01-31 18:13:56

0

这可能会帮助您:

import java.util.ArrayList; 
import java.util.Scanner; 
public class ABC { 

public static void main(String[] args) { 
    ArrayList<String> Animals = new ArrayList<String>(); 
    Animals.add("Tiger"); 
    Animals.add("Lion"); 
    String input = null; 
    System.out.println("Enter the name of the animal : "); 
    Scanner in = new Scanner(System.in); //Getting the name from the user 
    input = in.nextLine(); 
    if (Animals.contains(input)) {  //Checking for presence 
     System.out.println("Present"); 
    }else 
     System.out.println("Absent"); 
    } 
}