如何读取文本文件中的特定单词,并使用条件语句做某事



我是java编程新手。有人能帮我破译密码吗?我目前正在制作一个程序,您在jTextArea中输入字符串,如果输入的单词(s)与文本文件中的单词匹配,那么它将做一些事情。

例如:我输入单词"Hey",然后当输入的单词与文本文件匹配时,它会打印出类似"Hello"的东西。

我希望你明白我的意思。

下面是我的代码:

String line;
    String yo;
    yo = jTextArea2.getText();
    try (
        InputStream fis = new FileInputStream("readme.txt");
        InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
        BufferedReader br = new BufferedReader(isr);
    ) 
    {
        while ((line = br.readLine()) != null) {
            if (yo.equalsIgnoreCase(line)) {
                System.out.print("Hello");
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(ArfArf.class.getName()).log(Level.SEVERE, null, ex);
    }

一行不能使用等号,因为一行包含很多单词。你必须修改它来搜索一行中单词的索引。

       try (InputStream fis = new FileInputStream("readme.txt");
                InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
                BufferedReader br = new BufferedReader(isr);) {
            while ((line = br.readLine()) != null) {
                line = line.toLowerCase();
                yo = yo.toLowerCase();
                if (line.indexOf(yo) != -1) {
                    System.out.print("Hello");
                }
                line = br.readLine();
            }
        } catch (IOException ex) {
        }

既然你是java新手,我建议你花点时间学习java 8,它能让你写出更干净的代码。下面是用Java 8编写的解决方案,希望能给一点帮助

        String yo = jTextArea2.getText();
        //read file into stream, 
        try (java.util.stream.Stream<String> stream = Files.lines(Paths.get("readme.txt"))) {
            List<String> matchLines = stream.filter((line) -> line.indexOf(yo) > -1).collect(Collectors.toList()); // find all the lines contain the text
            matchLines.forEach(System.out::println); // print out all the lines contain yo
        } catch (IOException e) {
            e.printStackTrace();
        }
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class WordFinder {
    public static void main(String[] args) throws FileNotFoundException {
        String yo = "some word";
        Scanner scanner = new Scanner(new File("input.txt")); // path to file
        while (scanner.hasNextLine()) {
            if (scanner.nextLine().contains(yo)) { // check if line has your finding word
                System.out.println("Hello");
            }
        }
    }
}

最新更新