I've no idea if your algorithm is OK, but you're getting that output because you're printing out a character array. Arrays don't automatically print out in a helpful way in Java - what you're seeing is the result of the default implementation of toString() in Object.

Since it's a char array, there's an easy way to get it back into a String, though:

Out of interest, why are you declaring ch and res at the class level? They're only needed within the method, so your code would be more readable and maintainable if you declared them when they are used.

Alex Mokosh
Greenhorn

Joined: Feb 06, 2012
Posts: 4

posted Feb 06, 2012 10:35:10

0

I fixed it,thanks, now I got some normal output bcdb, but it's wrong, should be abcd, so can you find some error in my code??

Is your line 14 supposed to swap two values? Because at the moment it overwrites ch[j] with ch[j - 1], which means that whatever you had in the array at ch[j] is lost. That's where the 'a' has gone.

Incidentally, the way I did that was to step through the code line-by-line, writing down the value of all the variables at each step. If you've got access to a debugger it's even easier - that will step through the code for you and you can check the value of variables whenever you like.

Can't figure what out? The swapping part that Matthew is talking about? Imagine that you have two ping-pong balls--one red and one green. Now imagine that you have some cups, each just big enough to hold one ping-pong ball. You put the red ball in the cup labeled 'A' and the green ball in the cup labeled 'B'. Now you want to switch them, so red is in B and green is in A. Each ball always has to be in a cup, or it will roll away and you'll lose it. How would you do that?

Please don't do that. This site is NotACodeMill.(⇐click) Just handing somebody the solution doesn't help him learn. And, as it clearly states on the topics page, "We're all here to learn, so when responding to others, please focus on helping them discover their own solutions, instead of simply providing answers."

Not any more. In view of what Jeff Verdegan has just told you, I have gone back and edited your post. Please remember people learn less by being given a complete answer like that. Your code would not have helped at all, I am afraid.

Jeff Verdegan wrote: Please don't do that. This site is NotACodeMill.(⇐click) Just handing somebody the solution doesn't help him learn. And, as it clearly states on the topics page, "We're all here to learn, so when responding to others, please focus on helping them discover their own solutions, instead of simply providing answers." . . .