Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

An unexpected error in a sorting program in java

This is a program to sort every word in a sentence in ascending order.

import java.util.Scanner;
import java.util.Arrays;
class sorteveryword
   {
       void main()
       {
           Scanner sc=new Scanner(System.in);
           System.out.println("Enter the string");
           String str=sc.nextLine();
           String arr[]=str.split(" ");
           int l=arr.length;
           for(int i=0;i<l;i++)
           {
               String w=arr[i];
               char ch[]=w.toCharArray();
               Arrays.sort(ch);
               System.out.print(ch+" ");
            }
        }    
    }   

This code seems perfect to me but when I am printing something it is showing this output.

Enter the string
ab bc
[C@55fba33b [C@51c42d5c 

I really don’t know why this is happening.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Please help. And also please provide an alternative.

I want the output as

Enter the string
your eyes
oruy eesy

>Solution :

The easiest way to achieve what you want is to construct a new String from your sorted char array and print that String:

System.out.print(String.valueOf(ch)+" ");

See: https://ideone.com/4Mgoye
for an example.

Arrays by default do not provide an override for the toString() method and will use the default implementation of java.lang.Object – See How do I print my Java object without getting "SomeType@2f92e0f4"? for more background information on this.

While Strings themself of course can get printed without problems, so using Sting.valueOf to generate a String from your char array will allow you to print that String without much hassle.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading