【发布时间】:2021-06-16 03:54:56
【问题描述】:
Hi all so I have a list that looks like this screenshot
基本上,我试图接受用户输入的日期,一旦搜索我想要打印出它旁边的数字的日期。问题是我的 ArrayList 不能用 contains() 方法搜索而不输入整行,而不仅仅是日期。
public class SPX {
public static void main(String[] args) throws IOException {
ArrayList<String> dates = new ArrayList<>();
BufferedReader read = null;
try {
read = new BufferedReader(new FileReader("C:\\Users\\rosha\\eclipse-workspace\\working\\src\\workingFix\\spx_data_five_years (1).txt"));
String str;
//reading to the ArrayList
while ((str = read.readLine()) != null) {
String[] lineValues = str.split(str, 1);
dates.add(lineValues[0]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (read != null) {
try {
read.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//printing out the list
for (String dList:dates) {
System.out.println(dList);
}
findIndex(dates);
}
public static void findIndex(ArrayList<String> dates) {
Scanner sr = new Scanner(System.in);
System.out.println("please enter a date: ");
String userDate = sr.nextLine();
sr.close();
if (dates.contains(userDate)) {
System.out.print("Spx Index: " + userDate);
}
else {
System.out.print("Not found");
}
}
}
11/25/2014 2067.03
11/26/2014 2072.83
11/28/2014 2067.56
12/1/2014 2053.44
12/2/2014 2066.55
12/3/2014 2074.33
12/4/2014 2071.92
12/5/2014 2075.37
12/8/2014 2060.31
12/9/2014 2059.82
12/10/2014 2026.14
这些数字是文本文件的一部分,图片显示了它的格式。如果给定一个特定的日期,我想打印出它旁边的值。希望得到一些关于如何实现这一点的指导。任何帮助将不胜感激。
【问题讨论】:
-
您可以将数据读入
Map<String, String>,其中日期为键,数字为值。 Maps 是专门为这种需要链接到键值关系中的值的情况而设计的数据类型。 -
如何将第一个键与 ArrayList 中的值分开?我需要在空格之间拆分吗?
-
是的,按空格分割是正确的方法。见:How to split a string with any whitespace chars as delimiters
标签: java file arraylist compare contains