3

My code returns entrySet() as expected if called from within its own class. However if i call it via a getter method in Main it returns an empty table. Why?

class Results
{
    Hashtable<String, Double> langScores ;

    public Results()
    {
        langScores = new Hashtable<String, Double>() ;
    }

    public void addScores(double pL1, double pL2, double pL3)
    {
        langScores.put("English", pL1 ) ;
        langScores.put("French", pL2 ) ;
        langScores.put("German", pL3 ) ;
        System.out.println(langScores.entrySet()) ;
    }

    public Set<Map.Entry<String, Double>> getWinner()
    {
        return langScores.entrySet() ;
    }
}

MAIN:

class LanguageIdentifier 
{
    public static void main(String[] args) 
    {
        Results winner = new Results() ;

        AnalyseText analyse = new AnalyseText() ; //addScores called from this class

        analyse.analyseText() ;
        System.out.println(winner.getWinner()) ;
    }
}

OUTPUT

[German=0.0040, French=0.0030, English=0.02] // print statement within Results class works

[] // print statement within Main class prints empty table !?
4
  • Where do you call addScores() in your MAIN snippet? Commented Apr 23, 2011 at 23:53
  • addScores is called from AnalyseText class and works correctly given that i get a filled table back. Also note that the print statement in Result class is after the add statements to show that htese work. Commented Apr 24, 2011 at 0:00
  • 1
    But you don't pass the Results to the AnalyseText class. You are calling addScores() on a different object to the one that on which you're calling getWinner(). Commented Apr 24, 2011 at 0:01
  • yes indeed, i realise that now. must think of a way of making the hashtable object independant, if there is such a thing Commented Apr 24, 2011 at 0:05

2 Answers 2

2

In your main you didn't put any scores in winner (using addScores), so it's still empty.

Adding the line winner.addScores(1, 2, 3); fixed it for me.

As sjr mentioned, and according to your edit, you don't pass a reference to the Results object to the analyse object in creation, change the AnalyseText constructor to receive Results object as a parameter, and set the private Result reference of TextAnalyser to this object:

Results winner;
public TextAnalyser(Results winner)
{
    this.winner = winner;
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks. i was not thinking in OO terms and thought the Hashtable langScores would be Object independant
0

This happens because the instance of Results in the main method is diferent as the instance in AnalyseText object.

This is OO basic.

Comments

Your Answer

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