Hi Java warriors,
Just to make some of my actions more clear:
I called isGreaterThan() just to cover the requirement, in fact - my code doesn't need this check (maybe I'm wrong, it's possible tho).
So, I'd highly appreciate it if anyone would help me to fix my code, by editing:
//populating the final ArrayList.
Otherwise, I should refactor the entire code, anyway, any assistance is welcome.
TY in advance!
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>();
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) {
//creating two ArrayLists to split strings and integers
ArrayList<String> str = new ArrayList<>();
ArrayList<Integer> ints = new ArrayList<>();
ArrayList<Object> objects = new ArrayList<>();
//splitting and adding strings and integers
for (String item : array) {
if (isNumber(item)) {
ints.add(Integer.parseInt(item));
} else {
str.add(item);
}
}
//sorting num ArrayList.
isGreaterThan(array[0], array[1]);
Collections.sort(ints);
Collections.reverse(ints);
//sorting str ArrayList.
Collections.sort(str);
//merging two ArayLists into final Arraylist 'objects'.
objects.addAll(str);
objects.addAll(ints);
//populating the final ArrayList.
for (Object s1 : objects){
System.out.println(s1);
}
}
// 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;
}
}