j'ai écrit un message avant avec une version beaucoup plus rudimentaire du code ci-dessous.chaînes Arranger par ordre croissant et décroissant à l'aide des listes de tableau
Je réarrangées, mais il ne fonctionne toujours pas. Chaque fois que je saisis une nouvelle chaîne, elle n'apparaît dans aucune des deux listes. Il me donne ceci:
Voici vos chaînes en ordre croissant: []
Voici vos chaînes dans l'ordre décroissant: []
public class Stringseries {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Start the sequence by inputting a string DIFFERENT than 'quit'. When you DO want to end it, input 'quit'");
String encore = scanner.nextLine();
List<String> ascending = new ArrayList<>();
List<String> descending = new ArrayList<>();
int loop = 0;
String longest = "";
String lastInput = "";
boolean inserted = false;
while (!encore.equalsIgnoreCase("quit")) {
loop = ++loop;
encore = encore.replaceAll("\\s+",""); // this way, the length of the strings is only defined by the characters in the string, and not characters + whitespaces.
for(int i = 0; i < ascending.size(); i++) {
if(ascending.get(i).length() > encore.length()) {
ascending.add(i, encore);
inserted = true;
} if(!inserted) {
ascending.add(encore); }
} for(int i = 0; i > descending.size(); i++) {
if(descending.get(i).length() < encore.length()) {
descending.add(i, encore);
inserted = true;
} if(!inserted) {
descending.add(0, encore); }
}
if (longest.length() < encore.length()) {
longest = encore; }
System.out.println("Enter the string you want to put in your sequence of strings");
encore = scanner.nextLine();
}
if (descending != null) { // we check to see if the "descending" string is empty (we could do this with "ascending" mind you).
System.out.println("Here are your strings in ascending order : " + ascending);
System.out.println("Here are your strings in descending order : " + descending);
System.out.println("Here is the longest string : " + longest);
} else if (descending == null) {
System.out.println("You have not entered any strings, therefore the program doesn't display any string :("); // customised message.
}
}
}
Vous n'avez pas besoin null vérifiez que vous avez 'descendu' comme vous l'avez initialisé avec 'new ArrayList' –
Que diriez-vous de ne pas enregistrer 'descending' et simplement imprimer la collection dans l'ordre inverse? – cypher