简体   繁体   中英

Array of strings in Java NULL pointer exception

I want to make an array of strings

I do not have a fixed size for it

As it must be initialized, I intialize it with null .. it give java null pointer exception ???

in another part of my code , I loop on the array to print its contents.. so how to get over this error without having a fixed size

   public static String[] Suggest(String query, File file) throws FileNotFoundException
{
    Scanner sc2 = new Scanner(file);
    LongestCommonSubsequence obj = new LongestCommonSubsequence();
    String result=null;
    String matchedList[]=null;
    int k=0;

    while (sc2.hasNextLine()) 
    {
        Scanner s2 = new Scanner(sc2.nextLine());
        while (s2.hasNext()) 
            {
            String s = s2.next();
            //System.out.println(s);
            result = obj.lcs(query, s);

                if(!result.equals("no match"))
                {matchedList[k].equals(result); k++;}

            }
        return matchedList;
    }
    return matchedList;
}

If you don't know the size, List is always better.

To avoid NPE, you have to initialize your List like this :

List<String> matchedList = new ArrayList<String>(); 

ArrayList is a example, you can use all king of list you needed.

And to get your element instead of matchedList[index] you will have this :

macthedList.get(index);

So our code it will be like this :

public static String[] Suggest(String query, File file) throws FileNotFoundException
{
...
List<String> matchedList= new ArrayList<String>();
...

while (sc2.hasNextLine()) 
{
    Scanner s2 = new Scanner(sc2.nextLine());
    while (s2.hasNext()) 
    {
        ...
        if(!result.equals("no match")){
          //This line is strange. See explanation below
          matchedList.get(k).equals(result);
          k++;
         }
    }
    return matchedList;
}
return matchedList;
}

There is something strange in your code :

matchedList.get(k).equals(result);

When you do that, you compare both value and it will return true or false. It's possible that you want to add the value on your list, in this case you have to do it like this :

matchedList.add(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM