comparing string to array of strings using .equals() method
I am trying to compare an array of strings (a csv file of stock market symbols that was imported into an arraylist and then converted to an array) but it does not seem to be working. Am I not comparing it to the correct data type or something? Here is my code:
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
Any help is greatly appreciated
First, make sure your elements are filled properly. For example - without any whitespaces (use trim()
)
Then you can use something simpler: elementsList.contains(sym)
.
Don't use StringTokenizer
; instead use String#split
. Also, make sure you trim your values (both user input and each token) to account for spurious whitespaces. In Java, class names start with upppercase characters. You never close your Reader
, bad thing.
精彩评论