在文件中查找特定号码

您好,我正在尝试在 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();

    }

}


BIG阳
浏览 143回答 3
3回答

江户川乱折腾

您代码中的问题出在 while 块中:&nbsp; &nbsp; while(scanner.hasNextLine()){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //This first call returns 13/04/2000-2799&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(scanner.nextLine().trim().contains(year)){//This line finds matching value&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //But this line prints the next line&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(scanner.nextLine());//this call returns 06/10/1999-123&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }您可以做的是将您需要的值存储在一个变量中,如果它与年份匹配,则打印它:&nbsp; &nbsp; while(scanner.hasNextLine()){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //You store the value&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String value = scanner.nextLine().trim();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //See if it matches the year&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(value.contains(year)){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //Print it in case it matches&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(value);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }希望这可以帮助。

慕田峪4524236

您使用了 scanr.nextLine() 两次。那是一个错误。每次迭代仅调用一次并将结果分配给 String 值以供使用。

慕斯王

您调用了scanner.nextLine()两次,这意味着一旦找到匹配的行,您实际上是在打印下一行。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java