简体   繁体   English

使用数组列表按升序和降序排列字符串

[英]Arranging strings in ascending and descending order using array lists

I wrote a post before with a much more rudimentary version of the following code.我之前写过一篇文章,其中包含以下代码的基本版本。

I rearranged it, but it still doesn't work.我重新排列了它,但它仍然不起作用。 Whenever I input a new string, it doesn't go in either of the two lists.每当我输入一个新字符串时,它都不会出现在两个列表中。 It gives me this :它给了我这个:

Here are your strings in ascending order : [ ]以下是按升序排列的字符串:[]

Here are your strings in descending order : [ ]以下是按降序排列的字符串:[]

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

I would suggest you to sort the list using Collections.sort();我建议您使用Collections.sort();对列表进行排序Collections.sort(); and Collections.reverse();Collections.reverse(); Also, you don't need the else if (descending == null) since you already initialized descending .此外,您不需要else if (descending == null)因为您已经初始化了descending Your code will look something like,你的代码看起来像,

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();
 }
}

However I would use only one list instead of 2, Since they both have same elements.但是我只会使用一个列表而不是 2,因为它们都有相同的元素。 Like,像,

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();
 }
}

Hope it helps!希望有帮助!

Thanks to @phflack for pointing out the sort should be on length & not on lexical order.感谢@phflack 指出排序应该是长度而不是词法顺序。

Your code is almost correct To implement the insertion sort, you just need to move your if statement out of your loop, and to reset your inserted variable您的代码几乎是正确的要实现插入排序,您只需要将 if 语句移出循环,并重置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);

Other things of note with your code:您的代码的其他注意事项:

  • loop = ++loop; is normally written as loop++;通常写成loop++; instead相反
  • if(descending != null) will never be false, you're setting it to something with List<String> descending = new ArrayList<>(); if(descending != null)永远不会是假的,你将它设置为List<String> descending = new ArrayList<>(); at the top, instead it looks like you meant to write if(!descending.isEmpty())在顶部,看起来你打算写if(!descending.isEmpty())
  • Writing if(descending != null){ A } else if(descending == null){ B } is the same as (if descending != null){ A } else { B }if(descending != null){ A } else if(descending == null){ B }(if descending != null){ A } else { B }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM