This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
I have had to remove some of your code tags because the long line is very difficult to read in side code tags.
Please explain the rules you want to apply to printing. If a value is on the left, then you prepend it with a < and if it is the right branch a >? And the number of arrowheads depends on the depth you find that value at? And your nine‑element tree prints such a long
I would suggest you get a pencil and paper, going through that tree and working out how you are going to get a String together. It looks to me like a prime candidate for recursion. So start by working out how you are going to print a base case, for example a tree which looks like this:-Remember that tree will be represented by a node with its left and right references both pointing to null. Once you have got that working, see how you would print trees likeor
I would suggest you don’t use the + operator on Strings, because of performance problems. You might not notice anything in that little tree, but it won’t scale to large trees. Use a StringBuilder instead and use its append and insert methods. Note most of the StringBuilder methods do not return void, so you can daisy‑chain callsWarning: do not try passing a char to a StringBuilder constructor.
Note: You can pass a CharSequence to many methods of a StringBulider’s; since StringBulider itself implements CharSequence, that means you can easily append (for example) one StringBuilder to another.
Note 2: You can append or insert characters like | or a line end sequence. The best way to get the line end sequence is probably like this:-
private final String LINE_END = System.getProperty("line.separator"); Check that line carefully in case I have got a misspelling in it.
Aj Prieto wrote:What I need help on, is why does it print it out that way? Is my method wrong...[?]
Well, fairly obviously, it is.
And that's not just a flip comment. If a program is not doing what you want, it's almost always because your code is wrong; so don't start looking to blame anything outside until you can prove that it works; which in your case, you plainly can't.
However, just off the top of my head, I'd say that the heart of your problem lies in trying to do it all in one String. The required output is divided into lines, so I would look to creating an array (or List, or maybe even a Map) of Strings, where each one is a line, and then try to join them all.
I suspect there are several possible solutions though.