An unexpected error in a sorting program in java [duplicate]
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.
Please help. And also please provide an alternative.
I want the output as
Enter the string
your eyes
oruy eesy
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.