So the logic should be corect. At first I got the right output, but without using the "isGreaterThan" method and intead just using an ArrayList and Collection.sort(). I rewrote the same logic to use the "isGreaterThan" method. But now it doesn t stop from accepting inputs (see code below)
Thanks in advance!
package com.codegym.task.task09.task0930;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/*
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) {
// write your code here
ArrayList<Integer> intIndexes = new ArrayList<>();
ArrayList<Integer> stringIndexes = new ArrayList<>();
for (int i = 0; i < array.length ; i++) {
if(isNumber(array[i])){
intIndexes.add(i);
}else{
stringIndexes.add(i);
}
}
ArrayList<Integer> numbers = new ArrayList<>();
ArrayList<String> words = new ArrayList<>();
for (int i = 0; i < array.length ; i++) {
if(isNumber(array[i])){
numbers.add(Integer.parseInt(array[i]));
}else{
words.add(array[i]);
}
}
Collections.sort(numbers);
Collections.sort(words);
Collections.reverse(numbers);
int j = 0;
for (int i = 0; i < intIndexes.size(); i++) {
array[intIndexes.get(i)] = Integer.toString(numbers.get(i));
}
for (int i = 0; i < intIndexes.size(); i++) {
array[stringIndexes.get(i)] = words.get(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;
}
}