File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Sorting a string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Sorting a string" Watch "Sorting a string" New topic
Author

Sorting a string

feda alshahwan
Ranch Hand

Joined: Jul 26, 2008
Posts: 170
I am trying to enter a string then output should be the string ordered suppose you enter CDAB output should be ABCD my code is not sorting the string ??

my code is as follows


Compiling 1 source file to C:\Documents and Settings\Moon\My Documents\NetBeansProjects\order1\build\classes
compile:
run:
Enter Your Name :
CADH
Name after reordering is:CADH
BUILD SUCCESSFUL (total time: 12 seconds)

[HENRY: Added Code Tags]
[ August 08, 2008: Message edited by: Henry Wong ]
Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 30752
    
156


This method doesn't do anything. It assigns first and second different values but only within the swap method. It doesn't swap the references in the calling code.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Norm Radder
Ranch Hand

Joined: Aug 10, 2005
Posts: 687
    
    1
Look up the terms "call by reference" and "call by value". Youcould be a C programmer because your code assumes the method is called by reference.
To use your method logic, you'll have to pass the full string to the method along with the indexes of the chars to be swapped. Then build and return a new string with those chars swapped.
feda alshahwan
Ranch Hand

Joined: Jul 26, 2008
Posts: 170
How to fix the problem if I can not pass by reference. Can you guide me please?
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42264
    
  64
A method definition like this would work:


Ping & DNS - my free Android networking tools app
Graeme Byers
Ranch Hand

Joined: Apr 16, 2004
Posts: 127
The ranchers' diagnosis of your bug is correct.
However with mutable objects (even when marked final):

Your code could be simplified :
Norm Radder
Ranch Hand

Joined: Aug 10, 2005
Posts: 687
    
    1
Arrays.sort(charArray) ;


How does the OP learn how to code if he uses a built in method?
beginners need to do it the hard way first to learn how to loop and index.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Sorting a string