簡體   English   中英

按升序和降序排列字符串

[英]arranging strings in ascending and descending order

好吧,所以我的代碼不起作用:我試圖在“降序”和“升序”中排列輸入的字符串,但有時字符串不會出現在列表中(按正確的順序或不完全進入降序/升序字符串)

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 內置了可以做到這一點的東西,最顯着的是這里的 Stream API 和比較器

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

假設您想自己做事,因為這似乎是一項練習任務。 否則使用 j.seashell 的答案。

您當前的代碼只能將值輸入到列表的末尾。 這意味着如果你輸入

測試

第二次測試

第三次測試

前兩個輸入后的結果將是

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

你的下一個值應該在這兩者之間,所以正確的結果變成

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

但您的代碼現在可能只附加到字符串。 您還可以過濾掉尚未輸入的最短或最長字符串的字符串。 要解決這個問題,您必須實現某種方法來拆分列表,並在拆分的值中間插入值。 這可以通過多種方式完成,例如

最簡單的方法是使用 Java 內置的 List 結構,即List<String> ascending = new ArrayList<>(); 將字符串插入正確位置的可能解決方案可能是

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

您可以使用相同的循環,但將比較切換為<以獲取降序列表。

最后,您可以打印值

for(String value : ascending) {
    System.out.println(value);
}
/*
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
*/

使用鏈表。 每次添加單詞時,一次查看列表中的一項,並在位置 n 插入新節點,其中 n-1.length => n.length > n+1.length 要向后閱讀,您可以將其實現為雙向鏈表,或將單鏈表讀入堆棧並從堆棧中彈出

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM