3 回答

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超5個(gè)贊
您代碼中的問題出在 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
}
}
您可以做的是將您需要的值存儲(chǔ)在一個(gè)變量中,如果它與年份匹配,則打印它:
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);
}
}
希望這可以幫助。

TA貢獻(xiàn)1875條經(jīng)驗(yàn) 獲得超5個(gè)贊
您使用了 scanr.nextLine() 兩次。那是一個(gè)錯(cuò)誤。每次迭代僅調(diào)用一次并將結(jié)果分配給 String 值以供使用。

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超2個(gè)贊
您調(diào)用了scanner.nextLine()
兩次,這意味著一旦找到匹配的行,您實(shí)際上是在打印下一行。
添加回答
舉報(bào)