如何从文件中找到特定单词的行号

问题描述 投票:0回答:1

如何从文件中找到特定单词的行号。我希望能够打印出用户输入的单词的行号

    private static void Excerise04(String fname) throws FileNotFoundException {
        Scanner userinput = new Scanner(System.in);
        System.out.println("Enter First Word");
        String firstWord = userinput.nextLine();
        System.out.println("Enter Second Word");
        String secondWord = userinput.nextLine();
        Scanner filescanner = new Scanner(new File(fname));
        List<String> set = new ArrayList<>();
        while (filescanner.hasNext()) {
            String line = filescanner.nextLine();
            set.add(line);
        }
        set.forEach(System.out::println);
        userinput.close();
    }
}

它应该打印出用户输入的行号,如果没有找到它,它将打印出一个 system.out.println 说 ERROR

java java.util.scanner user-input
1个回答
0
投票

如果你想要行号,那么你需要在阅读文件时计算文件的行数。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class LabProgram {

    private static void exercise04(String fname) throws FileNotFoundException {
        Scanner userinput = new Scanner(System.in);
        System.out.print("Enter word to search for: ");
        String word = userinput.nextLine();
        try (Scanner filescanner = new Scanner(new File(fname))) {
            int line = 0;
            List<Integer> set = new ArrayList<>();
            while (filescanner.hasNextLine()) {
                String text = filescanner.nextLine();
                line++;
                if (text.contains(word)) {
                    set.add(line);
                }
            }
            if (set.size() > 0) {
                System.out.printf("The word '%s' appears on these lines of file '%s':%n",
                                  word,
                                  fname);
                set.forEach(System.out::println);
            }
            else {
                System.out.printf("The word '%s' was not found in file '%s'.%n",
                                  word,
                                  fname);
            }
        }
    }

    public static void main(String[] args) {
        try {
            exercise04("textfile.txt");
        }
        catch (FileNotFoundException x) {
            x.printStackTrace();
        }
    }
}

这是我使用的文本文件:
(通过网站Hipster Ipsum获得。)

Lyft salvia occupy asymmetrical same hammock. Helvetica activated charcoal coloring book, man bun
hexagon marfa four dollar toast hoodie bruh vibecession etsy bushwick enamel pin. Blue bottle before
they sold out hell of, man braid bruh cupping semiotics hella art party. Praxis etsy ennui chillwave
stumptown vaporware chicharrones irony. Vinyl kombucha slow-carb, snackwave mukbang williamsburg
celiac whatever taiyaki blue bottle flannel gatekeep art party vegan. Flexitarian adaptogen blue
bottle, hell of yes plz drinking vinegar roof party shaman. Next level cray listicle vinyl, banh mi
tilde fixie.

DIY humblebrag ennui PBR&B, hella schlitz whatever chartreuse austin pok pok keytar farm-to-table
raclette jawn. Taxidermy man bun master cleanse single-origin coffee air plant waistcoat craft beer,
cloud bread blog truffaut small batch cray. Pickled cloud bread pork belly praxis. Praxis shabby
chic fam, tacos chambray single-origin coffee 90's kale chips kombucha neutra yes plz keytar
biodiesel schlitz affogato.

Seitan hoodie +1 yuccie kale chips affogato. Try-hard tote bag twee tattooed tofu etsy occupy ugh
slow-carb gentrify chicharrones air plant heirloom la croix farm-to-table. Vexillologist ennui
vaporware succulents sustainable mustache tote bag try-hard. Taxidermy semiotics Brooklyn hexagon
sus, williamsburg pork belly health goth green juice gluten-free irony gentrify yr mlkshk tilde.
Plaid meggings schlitz shabby chic listicle.

Cray microdosing mukbang wayfarers church-key edison bulb gluten-free viral celiac mumblecore.
Cliche wayfarers beard fixie crucifix PBR&B cray fingerstache keffiyeh disrupt thundercats. Pabst
normcore yes plz vibecession sartorial organic. Snackwave drinking vinegar JOMO readymade yes plz
street art heirloom mlkshk. Pop-up normcore franzen flannel DIY, pug street art tbh yr.

Paleo tattooed williamsburg tbh shabby chic master cleanse cold-pressed iPhone viral helvetica banh
mi tacos. Kale chips bitters chia jean shorts la croix, activated charcoal artisan synth pitchfork.
Cliche quinoa Brooklyn hella sustainable, everyday carry pickled twee. Four loko vexillologist
wayfarers stumptown food truck thundercats. Listicle flexitarian thundercats plaid meditation.
Godard irony craft beer, YOLO put a bird on it vexillologist vegan tumblr.

Dummy text? More like dummy thicc text, amirite?

这是一个示例运行:

Enter word to search for: yes
The word 'yes' appears on these lines of file 'textfile.txt':
6
12
23

请注意,yes 这个词在第 23 行出现了两次,但是问题指出只有该词出现的行号是相关的,而不是该词在该行出现的次数。

另请注意,搜索区分大小写。例如,如果您搜索单词 pabst,则不会找到它,因为该文件仅包含单词 Pabst。如果你想要不区分大小写,那么你可以将

text
转换为全部小写,即

text.toLowerCase()

另外,我不明白为什么需要用户输入两个词,所以上面的代码只搜索用户输入的一个词。说到用户输入,你应该关闭一个包裹

Scanner
System.in
,所以你应该删除这行代码:

userinput.close();
© www.soinside.com 2019 - 2024. All rights reserved.