The displayed words should be sorted in ascending order (using the provided isGreaterThan method).
In my opinion program does display words in ascending order.
PS: I have used .toLowerCase() because while I have tested it with different input (Cherry 1 a 3 Apple 22 0 Watermelon) it did not worked correctly. Deleting .toLowerCase() does not meet requirement anyway
Please help, I am so close
package com.codegym.task.task09.task0930;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
/*
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>();
String read;
while ((read = reader.readLine()) != null) {
if (read.isEmpty()) {
break;
}
list.add(read);
}
String[] array = list.toArray(new String[list.size()]);
sort(array);
for (String x : array) {
System.out.println(x);
}
}
public static void sort(String[] array) {
String[] arr = array;
String temp = "";
for (int i = 0; i < arr.length - 1; i++) {
if (isNumber(arr[i]) == true) {
for (int j = i + 1; j < arr.length - 1; j++) {
if (isNumber(arr[j]) == true) {
if (Integer.parseInt(arr[j]) > Integer.parseInt(arr[i])) {
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
} else if (isNumber(arr[i]) == false) {
for (int j = i + 1; j < arr.length - 1; j++) {
if (isNumber(arr[j]) == false) {
if (isGreaterThan(arr[i].toLowerCase(), arr[j].toLowerCase())) {
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
}
}
}
// 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;
}
}