0

Ok, I have this program that is supposed to store information about CDs that are available in txt file. The file stores the data in format 'artist[tab]album' on the same line. What I want to do, is to have user input search query, and the program return if the CD is in the database. So let's say we have Green Day[tab]American Idiot in .txt file on some line, and when users types in Green, the programs checks that file and returns true. But my problem is, my current algorithm requires the string to completely match, instead of partial. So the users needs to type Green Day[tab]American Idiot to get true on the query. How to fix it? Thanks. I am sure it is something I don't see as beginner.

This is the part of the program that manages the search in the array Artists, that contains all the data currently stored in the .txt file

 for (String e : artists){
        if(Arrays.asList(e).contains(search)){
         contains=true;   
        }
1
  • 1
    With your current data structure, it looks like there's not really an alternative to looping through the array and calling .contains() on each string. (This will be fine for small arrays, but may cause performance issues for larger ones.) Commented Sep 23, 2015 at 17:36

1 Answer 1

2

Why are you creating a list? You should use artist.contains(search) (yes, try to choose more relevant variable names). Also make sure you don't have null elements in the array or search is not null etc, but you can do something like:

for(String artist : artists) {
    if(artist.toLowerCase().contains(search.toLowerCase()) {
        contains = true;
        // break; <- you may want to break here
    }
}

You may want to toLowerCase() both of them for case-insensitive search.

Sign up to request clarification or add additional context in comments.

11 Comments

@TheLaw Thats because either artists is null (was not initialized and assigned an object) or your collection contains null. Check them.
Well I can't read minds so you will have to elaborate a bit. NPE means one of those variables is null. Double check which of them and why. Maybe search is null. Maybe one of your array elements is null. Maybe the array itself is null. Etc.
I create the array by calling a method and the number of elements in array is generated by this piece of code <code>for (int i=0; i < num; i++){ artists[i] = bReader.readLine(); }
Can you put a breakpoint before the loop and check the contents of the array and the value of search?
I did that, and both the variables are not empty and contain correct data, before reaching the NPE error.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.