Solved

# sort an array with float and string

Posted on 2011-10-04
268 Views
I have a array: 0, a, b, 1.2, 0.2, c
I'd like to sort them by number first, then by alphabetic
result should be:
0, 0.2, 1.2, a, b, c

How can I do this?
0
Question by:xiaoyunwu

LVL 47

Assisted Solution

You define Comparator which aligns the strings this way and then
use method Arrays.sort(array, Comparator)

0

LVL 3

Accepted Solution

0

Author Closing Comment

Thanks!
0

LVL 86

Expert Comment

0

Author Comment

I've tried out, and it worked. Thanks.
0

LVL 47

Expert Comment

This is the class with static method sortArray, which would sort
your array in the sense you want it (see output):

``````import java.util.Arrays;

public class MyString implements Comparable<MyString>  {
String s;
public MyString(String s){
this.s = s;
}

public String getString(){ return s;}

public int compareTo(MyString ms1){
float f = -1.0f;
float f1 = -1.0f;
String s1 = ms1.getString();
boolean first = true;
boolean second = true;

try{
f = Float.parseFloat(s);
} catch(Exception ex){
first = false;
}

try{
f1 = Float.parseFloat(s1);
} catch(Exception ex){
second = false;
}

if(first && !second)return -1;
if(!first && second)return 1;
if(first && second){
if(f<f1)return -1;
else return 1;
}
if((!first) && (!second)){
return s.compareTo(s1);
}

return 1;
}

public static String [] sortArray(String [] arr){
MyString[] myss = new MyString[arr.length];
for(int j=0; j<arr.length; j++){
myss[j]= new MyString(arr[j]);
}

Arrays.sort(myss);
String [] ss = new String[myss.length];

for(int j=0; j<arr.length; j++){
ss[j]= myss[j].getString();
}

return ss;

}

public static void main(String[] args) {
String [] ss = { "0", "c", "b", "1.2", "0.2", "a"};
ss = MyString.sortArray(ss);
for(String s: ss){
System.out.println(s);
}

}

}
``````

Output:
``````0
0.2
1.2
a
b
c
``````
0

Author Comment

Thank you very much, for_yan.
0

LVL 47

Expert Comment

You are always welcome.
0

## Featured Post

### Suggested Solutions

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input: