2017-10-12 3 views
0

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. 
     } 
    } 
} 
+0

Vous n'avez pas besoin null vérifiez que vous avez 'descendu' comme vous l'avez initialisé avec 'new ArrayList' –

+2

Que diriez-vous de ne pas enregistrer 'descending' et simplement imprimer la collection dans l'ordre inverse? – cypher

Répondre

1

Je voudrais vous suggérez de trier la liste en utilisant Collections.sort(); et Collections.reverse(); En outre, vous n'avez pas besoin else if (descending == null) depuis que vous avez déjà initialisé descending. Votre code ressemblera,

import java.util.ArrayList; 
import java.util.Collections; 
import java.util.Comparator; 
import java.util.List; 
import java.util.Scanner; 
public class Test2 { 
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 longest = ""; 

    List<String> ascending = new ArrayList<String>(); 
    List<String> descending = new ArrayList<String>(); 
    int loop = 0; 
    Comparator<String> comparator = new Comparator<String>() { 
    public int compare(String o1, String o2) { 
    return o1.length() - o2.length(); 
    } 
    } 


    String encore = ""; 
    while(true){ 
    loop++; 
    System.out.println("Enter the string you want to put in your sequence of strings"); 
    encore = scanner.nextLine(); 
    if (encore.equalsIgnoreCase("quit")) { 
    break; 
    } 

    encore = encore.replaceAll("\\s+", ""); // this way, the length of the strings is only defined by the characters in the string, and not characters + whitespaces 

    ascending.add(encore); 
    descending.add(encore); 
    Collections.sort(ascending, comparator); 
    Collections.sort(descending, comparator); 
    Collections.reverse(descending); 
    } 

    for (String str: ascending) { 
    if (str.length() > longest.length()) { 
    longest = str; 
    } 
    } 

    if (ascending.size() > 0) { 
    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 { 
    System.out.println("You have not entered any strings, therefore the program doesn't display any string :("); // customised message. 
    } 

    scanner.close(); 
} 
} 

Cependant, j'utiliser une seule liste au lieu de 2, Comme ils ont tous les deux mêmes éléments. Comme,

import java.util.ArrayList; 
import java.util.Collections; 
import java.util.Comparator; 
import java.util.List; 
import java.util.Scanner; 

public class Test2 { 
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 longest = ""; 

    List <String> list = new ArrayList < >(); 
    int loop = 0; 

    String encore = ""; 
    while(true){ 
    loop++; 
    System.out.println("Enter the string you want to put in your sequence of strings"); 
    encore = scanner.nextLine(); 
    encore = encore.replaceAll("\\s+", ""); // this way, the length of the strings is only defined by the characters in the string, and not characters + whitespaces 

    if (encore.equalsIgnoreCase("quit")) { 
    break; 
    } 
    list.add(encore); 
    } 

    for (String str: list) { 
    if (str.length() > longest.length()) { 
    longest = str; 
    } 
    } 

    if (list.size() > 0) { 
    Collections.sort(list, new Comparator<String>() { 
    @Override 
    public int compare(String o1, String o2) { 
    return o1.length() - o2.length(); 
    } 
    }); 
    System.out.println("Here are your strings in ascending order : " + list); 
    Collections.reverse(list); 
    System.out.println("Here are your strings in descending order : " + list); 
    System.out.println("Here is the longest string : " + longest); 
    } else { 
    System.out.println("You have not entered any strings, therefore the program doesn't display any string :("); // customised message. 
    } 

    scanner.close(); 
} 
} 

Espérons que ça aide!

Merci à @phflack pour souligner le genre devrait être la longueur & pas sur l'ordre lexical.

+0

Dans votre premier exemple, vous inversez constamment 'décroissant 'sans jamais le trier, vous pouvez également vouloir déplacer le tri et inverser à l'extérieur de la boucle. Vous devez également implémenter un comparateur pour trier par longueur au lieu de lexicographique – phflack

+0

@phflack Je l'ai fait dans mon deuxième exemple (marqué comme optimisé). – Sridhar

+1

@phflack Je pense que j'ai foiré quand j'ai ajouté un compartiment. Pardon :( – Sridhar

1

Votre code est presque correct Pour mettre en œuvre le type d'insertion, il vous suffit de déplacer votre instruction if de votre boucle, et pour réinitialiser votre variable inserted

inserted = false; 
for(int i = 0; i < ascending.size(); i++) 
    if(ascending.get(i).length() > encore.length()) 
    { 
     ascending.add(i, encore); 
     inserted = true; 
     break; 
    } 
if(!inserted) 
    ascending.add(encore); 

inserted = false; 
for(int i = 0; i > descending.size(); i++) 
    if(descending.get(i).length() < encore.length()) 
    { 
     descending.add(i, encore); 
     inserted = true; 
     break; 
    } 
if(!inserted) 
    descending.add(0, encore); 

Autres choses de note avec votre code:

  • loop = ++loop; est normalement écrit loop++; au lieu
  • if(descending != null) ne sera jamais faux, vous définissez à quelque chose avec List<String> descending = new ArrayList<>(); en haut, au lieu, il semble que vous vouliez écrire if(!descending.isEmpty())
  • écriture if(descending != null){ A } else if(descending == null){ B } est le même que (if descending != null){ A } else { B }