Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search String only prints out searches without characters attached

I’m new to java and I am working on a project. I am trying to search a text file for a few 4 character acronyms. It will only show or output when it’s just the 4 characters and nothing else. If there is a space or another character attached to it won’t display it… I have tried to make it show the whole line, but have yet to be successful.

The contents of text file:

APLM
APLM12345
ABC0
ABC0123456
CSQV
CSQVABCDE
ZIAU
ZIAUABCDE

The output in console:

APLM
ABC0
CSQV
ZIAU

My Code:

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;

public class searchPdfText
{
public static void main(String args[]) throws Exception
{
    int tokencount;
    FileReader fr = new FileReader("TextSearchTest.txt");
    BufferedReader br = new BufferedReader(fr);

    String s = "";
    int linecount = 0;
    ArrayList<String> keywordList = new ArrayList<String>(Arrays.asList("APLM",  "ABC0", "CSQV",  "ZIAU" ));

    String line;
    while ((s = br.readLine()) != null)
    {
        String[] lineWordList = s.split(" ");
        for (String word : lineWordList)
        {
            if (keywordList.contains(word))
            {
                System.out.println(s);

                break;
            }
        }
    }
}
}
like image 942
javajoejuan Avatar asked Dec 21 '25 21:12

javajoejuan


1 Answers

If you take a look at the documentation for ArrayList.contains you will see that it only returns true if your keyword contains the provided string from your file. As such, your code is correct when it only outputs the exact matches found for those provided strings in keywordList.

Instead, if you want to get matches when a part of the provided string contains a keyword, consider iterating through the input and matching it the other way around:

while ((s = br.readLine()) != null) {
    String[] lineWordList = s.split(" ");
    for (String word : lineWordList) {
        // JAVA 8
        keywordList.stream().filter(e -> word.contains(e)).findFirst()
                .ifPresent(e -> System.out.println(word));

        // JAVA <8
        for (String keyword : keywordList) {
            if (word.contains(keyword)) {
                System.out.println(s);
                break;
            }
        }
    }
}

Additionally, you may consider following Oracle's Java Naming Conventions with regards to your class name. Each word in your class name should be capitalized. For example, you class might be better named SearchPdfText.

like image 163
David Yee Avatar answered Dec 23 '25 13:12

David Yee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!