On line 9 you are calling a constructor that sets wordOne and wordTwo to null. Nowhere are you calling setWords() to change it to something other than null. The print on line 10 calls the toString() method will print out "null should be placed after null"
Jeremiah Waters wrote:
Just a doubt.
Carey Brown wrote:You might want to consider putting the logic in your compare() method directly into your toString() method and then do away with compare() and the member variable "compare". Seems like that would be cleaner.
I think the same.
Carey Brown wrote:however I still feel that toString() should call it otherwise there's nothing to guarantee that it is called before toString() is called.
Jeremiah Waters wrote:I'm trying to create a code that will compare two Strings to determine if the first word should be placed before or after the second word in the dictionary
So, in compare() remove the parameters seeing as how they are not being used. Then call compare() as I showed earlier and there shouldn't be any compile errors.
If you user input String two = "Ape"; which gives resulted output abe should be placed after Ape which is incorrect as per dictionary word order so better use compareToIgnoreCase(...) method.
That isn't an error, but an exception and it is a good thing to see. I am really pleased to see it because it tells me that you are actually calling compareTo() on one of your Strings.
Jeremiah Waters wrote:. . . But I am now receiving the error- . . .
It appears you haven't initialized those two String variables in the constructor. Will you please post the complete new updated code?
The only way to be certain that those Strings will be initialised is to do so via a constructor. Otherwise people will see your object and not even know they are supposed to call setWords() or compare(). Write a constructor taking those two Strings, and also calling the compare() method. That is also the only way to be certain that the compare field is not 0 for the whole life of the object.
How many constructors have you got? Count them.
. . . should I be making these changes to an existing constructor or writing an entirely new one?
If you haven't read any of these articles yet I would highly recommend it. Ultimately, the goal is to know it, not just guess at it.
Ganesh Patekar wrote:Worth reading The Java™ Tutorials: Providing Constructors for Your Classes or What is constructor in Java?
Jeremiah Waters wrote:Thank you so much! For both your help and your patience!
javadocs wrote:Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read.