gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:39:23 24 4
gpt4 key购买 nike

我正在尝试比较字符串数组(股票市场符号的 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

非常感谢任何帮助

最佳答案

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

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

关于java - 使用 .equals() 方法将字符串与字符串数组进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5463874/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com