使用.equals()方法将字符串与字符串数组进行比较

时间:2011-03-28 19:14:29

标签: java arrays

我正在尝试比较一个字符串数组(导入到arraylist然后转换为数组的股票市场符号的csv文件),但它似乎不起作用。我不是将它与正确的数据类型或其他东西进行比较?这是我的代码:

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.ArrayList;

public class search
{
    public static void main(String[] args)
    {
        try
        {
            //csv file containing data
            String strFile = "companylist.csv";

            //create BufferedReader to read csv file
            BufferedReader br = new BufferedReader(new FileReader(strFile));
            String strLine = "";
            StringTokenizer st = null;
            int lineNumber = 0, tokenNumber = 0;

            //create arraylist
            ArrayList<String> arrayList = new ArrayList<String>();

            //read comma separated file line by line
            while ((strLine = br.readLine()) != null)
            {
                lineNumber++;

                //break comma separated line using ","
                st = new StringTokenizer(strLine, ",");

                while (st.hasMoreTokens())
                {
                    //display csv values
                    tokenNumber++;
                    arrayList.add(st.nextToken());
                    //System.out.println("Line # " + lineNumber + ": "+ st.nextToken() + " " + st.nextToken());
                } //end small while

                //reset token number
                tokenNumber = 0;

            } //end big while loop

            //send csv to an array
            Object[] elements = arrayList.toArray();
            /*
            for(int i=0; i < elements.length ; i++)    {    
            System.out.println(elements[i]); 

            } */
            Scanner input = new Scanner(System.in);
            System.out.print("Enter Ticker symbol");
            String sym = input.next();

            for (int i = 0; i < elements.length; i++)
            {
                if (elements[i].equals(sym))
                {
                    System.out.println("match");
                }
            }
        }
        catch (Exception e)
        {
            System.out.println("Exception while reading csv file: " + e);
        }

    }//end main
}//end class

非常感谢任何帮助

2 个答案:

答案 0 :(得分:4)

首先,确保您的元素正确填充。例如 - 没有任何空格(使用trim()

然后你可以使用更简单的东西:elementsList.contains(sym)

答案 1 :(得分:2)

不要使用StringTokenizer;而是使用String#split。此外,请确保修剪您的值(用户输入和每个标记)以考虑虚假空白。在Java中,类名以upppercase字符开头。你永远不会关闭你的Reader,坏事。