I have a project for class were I need to get 4 different strings inputted and then output them in alphabetical order.
So far I have this:
String wd1
Since you are unable to use arrays or any other data structure and a sorting algorithm, you will need to do this manually with several if
statements. Before you try to write any code, I suggest you try doing this by hand. If I gave you four words, how would you determine which is the first one in alphabetical order? The second? Keep going; if you can describe how you do this in words, translating into Java should be straight-forward.
Edit:
Don't worry about ASCII code or anything computer related at the moment. I guess you do need to consider the detail that compareTo()
only lets you compare two words at a time, though. So let's say you pick wd1
and wd2
to compare. When you compare these two "words", what are the possible outcomes? In each case, what will you do next?
Another Edit:
After discussing in comments, you can see that the algorithm here is something like this (in pseudocode):
if wd1 comes before wd2
if wd1 comes before wd3
if wd1 comes before wd4
print out wd1 // wd1 is the first word in alphabetical order
else
print out wd4 // wd4 is the first word in alphabetical order
else
// Details left as an exercise to the reader
else
// Details left as an exercise to the reader
Finish filling in the else statements first in English following the same pattern illustrated here. When you have this finished, writing the code in Java should be pretty simple.
As you can see "understanding the concept" is often not enough to get you started writubg the code. You need to take the time figuring out all the excruciating details. Often I find it helps writing out the steps in English using pen and paper (or maybe a word processor) before I even start writing code. (Of course, you can use your own native language if that's easier. The point is to NOT jump on the computer and start writing Java code from the begginning, especially when you are stuck.)
When you can describe the steps in your native language, then translating into Java becomes easier. Sometimes it is trivial. Other times, you run into a detail that wasn't considered in your natural-language description. Then you back up away from the Java and fix the description before continuing with the Java.
This is basically the process I use when I'm trying to write a computer program. I hope you can adapt some of these ideas to your own coding.