简体   繁体   中英

Java File sometimes works and sometimes does not work

I am trying to make a sentiment analysis of a sentence. I am reading word's positive and negative values and then showing the result to the user as entered sentence is positive or negative. However, it works for some sentences ang gives exception for some other and I am really confused about it. My code is below. All implementations are done through this class. What should I do to solve it ?

And I have file something like boring 0.1 0.5 good 0.6 0.4 . . . When I write a boring book the output This sentence is negative

When I write a terrible car I get

a terrible car

File does not contain this word.!

 Exception in thread "main" java.lang.NullPointerException

 at SentimentAnalysis.posOrNeg(SentimentAnalysis.java:86)

 at SentimentAnalysis.main(SentimentAnalysis.java:121)

My file's content is

a 0.8 0.8

beautiful 0.3 0.01

car 0.1 0.1

boring 0.01 0.02

book 0.2 0.18

baby 0.8 0.6

cute 0.6 0.4

terrible 0.3 0.4

Judging by what's happening with your error:

Probability a = s.findProbabilities(words[k]);  
pos = pos*a.positive;   //ERROR LINE

the only reason why you'd get a null reference exception on that line is if a is null

in your findProbabilities method, you do a while loop which does some sort of searching. I didn't look too deeply into it because that's not the important part. The important part, is that it's possible for that method to return null if it doesn't find a match.

you can't access a.positive if a is null. You have to handle the null case. It can be something as simple as

if(a != null)
{
    pos = pos*a.positive;
    neg = neg*a.negative;
}
else
{
    // whatever you want to do if you can't find a
}

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