Hello,
The task ask me to use the "estSuperieurA()" or "isGreaterThan()" method to display words in ascending sort.
I did it, but the task don't validate my code...
Anyone can explain me please ??
package fr.codegym.task.task09.task0930;
import javax.swing.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
/*
Mission sur les algorithmes
*/
public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader lecteur = new BufferedReader(new InputStreamReader(System.in));
ArrayList<String> liste = new ArrayList<String>();
while (true) {
String s = lecteur.readLine();
if (s == null) break;
liste.add(s);
}
String[] tableau = liste.toArray(new String[0]);
tri(tableau);
for (String x : tableau) {
System.out.println(x);
}
}
public static void tri(String[] tableau) {
// écris ton code ici
ArrayList<String> words = new ArrayList<>();
ArrayList<Integer> numbers = new ArrayList<>();
//First solution - Sorting numbers
for (String s : tableau) {
if (estUnNombre(s)) {
numbers.add(Integer.parseInt(s));
}else {
words.add(s);
}
}
Collections.sort(numbers);
Collections.reverse(numbers);
//Second solution - Sorting words
for (int i = 0; i < words.size(); i++) {
String first = words.get(i);
for (int j = i + 1; j < words.size(); j++) {
if (estSuperieurA(first, words.get(j))) {
words.set(i, words.get(j));
words.set(j, first);
}
}
}
//Populating back the array with both arrayLists
int x = 0;
int y = 0;
for (int i = 0; i < tableau.length; i++) {
if (estUnNombre(tableau[i])) {
tableau[i] = String.valueOf(numbers.get(x));
x++;
}else {
tableau[i] = words.get(y);
y++;
}
}
}
// Méthode de comparaison de chaînes : 'a' est supérieur à 'b'
public static boolean estSuperieurA(String a, String b) {
return a.compareTo(b) > 0;
}
// La chaîne passée est-elle est un nombre ?
public static boolean estUnNombre(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 == '-') // La chaîne contient un trait d'union
|| (!Character.isDigit(c) && c != '-') // ou n'est pas un nombre et ne commence pas par un trait d'union
|| (i == 0 && c == '-' && chars.length == 1)) // ou est seulement un trait d'union
{
return false;
}
}
return true;
}
}