1) why is my code not working to sort the numbers in order from high to low? I did convert the String into an Integer so to be able to sort them as numbers instead of as chars which gave me the wrong results. What part am I missing?
2) It does sort the Strings but I fail to pass the task, why?
I hope someone can enlighten me, thanks in advance.
package com.codegym.task.task09.task0930;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
/*
Task about algorithms
*/
public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
ArrayList<String> list = new ArrayList<String>();
while (true) {
String s = reader.readLine();
if (s == null || s.isEmpty()) break;
list.add(s);
}
String[] array = list.toArray(new String[list.size()]);
sort(array);
for (String x : array) {
System.out.println(x);
}
}
public static void sort(String[] array) {
// Loop over the array with Strings and numbers
for(int i = 0; i< array.length; i++){
if(!isNumber(array[i])){//if the item is a String
for(int j = i+1; j < array.length -1; j++){ // to find the next String
if(isGreaterThan(array[i], array[j])){//call this method to compare which is greater
//if it returns -1 (false) swap the items
String temp = array[i];
array[i] = array[j];
array[j] = temp;
}
else {
continue;
}
}
}
else {//if it is a number sort from high to low
for(int j = i + 1; j < array.length -1; j++){ //to find the next number
//if(!isGreaterThan(array[i], array[j]))// call this method to check which one is greater
//{//if true swap the items problem is that it sorts only on first char.
//so I have to change the String into an Integer can't use the isGreaterThan()
int a = Integer.parseInt(array[i]);
int b = Integer.parseInt(array[j]);
if(a < b){
int temp = a;
a = b;
b = temp;
}
else{
continue;
}
}
}
}
}
// String comparison method: 'a' is greater than 'b'
public static boolean isGreaterThan(String a, String b) {//it returns an integer
return a.compareTo(b) > 0;//if a>b return 1 if b>a return -1 if equal retuns 0
}
// Is the passed string a number?
public static boolean isNumber(String s) {//it returns true or false but does parse the String into an Integer
if (s.length() == 0) return false;
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if ((i != 0 && c == '-') // The string contains a hyphen
|| (!Character.isDigit(c) && c != '-') // or is not a number and doesn't start with a hyphen
|| (i == 0 && c == '-' && chars.length == 1)) // or is a single hyphen
{
return false;
}
}
return true;
}
}