您好,我正在尝试在Java中循环播放文件,并且仅输出其年份为2000的字符串。
由于某些原因,当我执行.trim().compare(year)
时,它仍会返回所有字符串。我不知道为什么
文件中字符串的示例为
20/04/1999-303009
13/04/2000-2799
06/10/1999-123
例如,在这3个文件中,我只想获取13/04/2000-2799
(请注意文件很大)
这是到目前为止我想出的代码:
public static void main(String[] args) throws IOException {
//Initiating variables
String filedir =("c://test.txt");
ArrayList<String> list = new ArrayList<String>();
String year = "2000";
try (Scanner scanner = new Scanner(new File(filedir))) {
while (scanner.hasNextLine()){
// String[] parts = scanner.next().split("-");
if (scanner.nextLine().trim().contains(year)) {
System.out.println(scanner.nextLine());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
答案 0 :(得分:2)
您两次使用scanner.nextLine()。那是一个错误。每次迭代仅调用一次,并将结果分配给String值以供使用。
答案 1 :(得分:1)
您要拨打scanner.nextLine()
两次,这意味着一旦找到匹配的行,您实际上是在打印下一行。
答案 2 :(得分:0)
您的代码中的问题在while块中:
while(scanner.hasNextLine()){
//This first call returns 13/04/2000-2799
if(scanner.nextLine().trim().contains(year)){//This line finds matching value
//But this line prints the next line
System.out.println(scanner.nextLine());//this call returns 06/10/1999-123
}
}
您可以做的是将所需的值存储在变量中,如果与年份匹配,则将其打印出来:
while(scanner.hasNextLine()){
//You store the value
String value = scanner.nextLine().trim();
//See if it matches the year
if(value.contains(year)){
//Print it in case it matches
System.out.println(value);
}
}
希望这会有所帮助。