When I submit my code all requirements pass except the following: "The displayed words should be sorted in ascending order (using the provided isGreaterThan method)."
I have, in fact, used the IsGreaterThan method and my output is exactly as shown in the task details when I use the example input data.
I would appreciate anyone's insight to the problem.
package com.codegym.task.task09.task0930;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
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>();
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) {
ArrayList<String> words = new ArrayList<>();
ArrayList<Integer> intList = new ArrayList<>();
int[] position = new int[array.length];
for (int i = 0; i < array.length; i++) {
if (isNumber(array[i])) {
intList.add(Integer.parseInt(array[i]));
position[i] = 1;
} else {
words.add(array[i]);
position[i] = 0;
}
}
// Sort the integer list
int tempInt = 0;
for(int i = 0; i <= intList.size(); i++) {
for(int j = 1; j <= (intList.size() - 1); j++) {
if(intList.get(j - 1) > intList.get(j)) {
tempInt = intList.get(j - 1);
intList.set(j - 1, intList.get(j));
intList.set(j, tempInt);
}
}
}
// Sort the word list
String tempWord = "";
for(int i = 0; i < words.size(); i++) {
for(int j = 1; j < (words.size() - 1); j++) {
if(isGreaterThan(words.get(j - 1), words.get(j))) {
tempWord = words.get(j - 1);
words.set(j - 1, words.get(j));
words.set(j, tempWord);
}
}
}
// Reverse the integer list
Collections.reverse(intList);
// Combine lists
String[] newArray = new String[array.length];
for(int i = 0; i < array.length; i++) {
if (position[i] == 1) {
newArray[i] = intList.get(0).toString();
intList.remove(0);
} else {
newArray[i] = words.get(0);
words.remove(0);
}
}
// replace original values in array with the sorted values
for(int i = 0; i < array.length; i++) {
array[i] = newArray[i];
}
}
// 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;
}
}