xiaoyunwu
asked on
sort an array with float and string
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?
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?
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Neither of those answers will help you unfortunately
ASKER
I've tried out, and it worked. Thanks.
This is the class with static method sortArray, which would sort
your array in the sense you want it (see output):
Output:
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
ASKER
Thank you very much, for_yan.
You are always welcome.
ASKER