My code works correctly based on the requirements when I run it. But I got an error when trying to verify it. Anyone has an idea?
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.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) {
for (int i = 0; i < array.length; i++) {
for (int j = i; j < array.length - 1; j++) {
String first = array[i];
String second = array[j];
if (!isNumber(first) && !isNumber(second)) {
String firstLetter1 = first.substring(0, 1);
String firstLetter2 = second.substring(0, 1);
if (isGreaterThan(firstLetter1, firstLetter2)) {
String tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
} else if (isNumber(first) && isNumber(second)){
if (Integer.parseInt(second) > Integer.parseInt(first)) {
String tmp = array[j];
array[j] = array[i];
array[i] = tmp;
}
}
}
}
}
// String comparison method: 'a' is greater than 'b'
public static boolean isGreaterThan(String a, String b) {
return a.compareTo(b) > 0;
}
// Is the passed string a number?
public static boolean isNumber(String s) {
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;
}
}