【问题标题】:arranging strings in ascending and descending order按升序和降序排列字符串
【发布时间】:2017-10-11 14:18:45
【问题描述】:

好吧,所以我的代码不起作用:我正在尝试以“降序”和“升序”排列输入的字符串,但有时字符串不会进入列表(以正确的顺序或它根本不进入降序/升序字符串)

import java.util.Scanner;
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(); 

    int loop = 0;

    String smallest = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; // we set a "smallest" string to know where to put the new string in the "descending" and "ascending" strings.
    String longest = "";
    String ascending = "";
    String descending = "";
    String lastInput = "";

    while (!encore.equals("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.

        if (loop == 1) {
            descending = encore;
            ascending = encore;
        } if (loop >= 2) {
            if (encore.length() < smallest.length()) {
                descending = descending + " " + encore;
                ascending = encore + " " + ascending;
            } if (encore.length() > longest.length()) {
                descending = encore + " " + descending;
                ascending = ascending + " " + encore;
            }
        }

        if (longest.length() < encore.length()) {
            longest = encore;
        } if (smallest.length() > encore.length()) {
            smallest = encore;
        }


        System.out.println("Enter the string you want to put in your sequence of strings");

        lastInput = encore;
        encore = scanner.nextLine();
    }

    if (descending != null && !descending.isEmpty()) { // 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 | descending == "") { 
        System.out.println("You have not entered any strings, therefore the program doesn't display any string :("); // customised message.
    }
  } // end Method
} // end Class

【问题讨论】:

标签: java string sorting


【解决方案1】:

我会采取完全不同的方法。你的是非常本土化的,Java 有内置的东西可以做到这一点,最值得注意的是,Stream API 和 Comparator

String quitString = "quit";
List<String> userInputList = new ArrayList<>();

try(Scanner scanner = new Scanner(System.in)){ // This is called a "try with resources"
    System.out.println("Start the sequence by inputting a string DIFFERENT than 'quit'. When you DO want to end it, input \"" + quitString + "\"." + System.lineSeparator());

    String encore = scanner.nextLine();

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

        encore = scanner.nextLine();
        if(encore != null && !encore.isEmpty() && !encore.equalsIgnoreCase(quitString)) {
            userInputList.add(encore);
        }
    }
}
catch(Exception e)
{
    e.printStackTrace();
}

List<String> ascending =
        userInputList.stream()
                .sorted((strA, strB) -> strA.length() - strB.length())
                .collect(Collectors.toList());

List<String> descending =
        userInputList.stream()
                .sorted((strA, strB) -> strB.length() - strA.length())
                .collect(Collectors.toList());

StringBuilder sbAscending = new StringBuilder();
sbAscending.append("Here are your strings in ascending order: ");
ascending.forEach(userInput -> {
    sbAscending.append(System.lineSeparator() + userInput);
});

System.out.println(sbAscending.toString());

StringBuilder sbDescending = new StringBuilder();
sbDescending.append("Here are your strings in descending order: ");
descending.forEach(userInput -> {
    sbDescending.append(System.lineSeparator() + userInput);
});

System.out.println(sbDescending.toString());

输出:

Start the sequence by inputting a string DIFFERENT than 'quit'. When you DO want to end it, input "quit".

Start
Enter the string you want to put in your sequence of strings
test
Enter the string you want to put in your sequence of strings
test2
Enter the string you want to put in your sequence of strings
test23
Enter the string you want to put in your sequence of strings
test234
Enter the string you want to put in your sequence of strings
quit
Here are your strings in ascending order: 
test
test2
test23
test234
Here are your strings in descending order: 
test234
test23
test2
test

【讨论】:

    【解决方案2】:

    假设您想自己做一些事情,因为这似乎是一项练习作业。否则使用 j.seashell 的答案。

    您当前的代码只能将值输入到列表的末尾。这意味着如果你输入

    测试

    第二次测试

    第三次测试

    前两个输入后的结果将是

    ascending = "Test SecondTest"
    descending = "SecondTest Test"
    

    你的下一个值应该介于这两者之间,所以正确的结果变成了

    ascending = "Test ThirdTest SecondTest"
    descending = "SecondTest ThirdTest Test"
    

    但您的代码现在只能附加到字符串。 您还可以过滤掉尚未输入的最短或最长字符串。为了解决这个问题,您必须实施某种方法来拆分列表,并将值插入到拆分值的中间。例如,这可以通过多种方式完成

    最简单的方法是使用 Java 内置的 List 结构,即 List&lt;String&gt; ascending = new ArrayList&lt;&gt;(); 将字符串插入正确位置的可能解决方案可能是

    boolean inserted = false;
    //We loop to the correct location and add it
        for(int i = 0; i < ascending.size(); i++) {
        if(ascending.get(i).length() > encore.length()) {
            ascending.add(i, encore);
            inserted = true;
            break;
        }
    }
    //If it wasn't inserted its the longest one yet, so add it at the end
    if(!inserted) { 
        ascending.add(encore);
    }
    

    您可以使用相同的循环,但将比较切换为 &lt; 以获得降序列表。

    最后你可以用

    打印值
    for(String value : ascending) {
        System.out.println(value);
    }
    

    【讨论】:

    • 好电话@Jotunacorn,我写我的时候没有考虑boolean isStudent
    【解决方案3】:
    /*
    Hello Mister Dracose.
    
    perhaps you should use something a bit more appropriated for this goal.
    
    in fact you can not manage more than 2 strings at a time on your currently code, so you rather be using  
    */
    List<String> supplierNames1 = new ArrayList<String>();
    /*
    java structures, for save all user inputs, before you can go any further.
    
    after that, than you could use your ordenating algotithm exatcly the same way you re already doing.
    
    hope this help
    */
    

    【讨论】:

      【解决方案4】:

      使用链表。每次添加单词时,一次向下查看列表中的一项,然后在位置 n 插入新节点,其中 n-1.length => n.length > n+1.length 要向后阅读,您可以将其实现为双向链表,或者将单链表读入堆栈并弹出堆栈

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-24
        • 2011-08-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-08
        • 2012-11-08
        相关资源
        最近更新 更多