简体   繁体   English

按升序和降序排列字符串

[英]arranging strings in ascending and descending order

Alright so my code doesn't work : I'm trying to arrange inputted strings in both a "descending" and an "ascending" but sometimes strings just won't go in the lists (either in the right order or it doesn't go in the descending/ascending strings at all)好吧,所以我的代码不起作用:我试图在“降序”和“升序”中排列输入的字符串,但有时字符串不会出现在列表中(按正确的顺序或不完全进入降序/升序字符串)

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

I would take a different approach entirely.我会采取完全不同的方法。 Yours is very homegrown, and Java has stuff built in that can do this, most notably here, the Stream API and Comparators你是非常本土化的,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());

Output:输出:

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

Assuming you want to do stuff by your self, since this seems to be a practice assignment.假设您想自己做事,因为这似乎是一项练习任务。 Otherwise use j.seashell's answer.否则使用 j.seashell 的答案。

Your current code can only input values into the end of the lists.您当前的代码只能将值输入到列表的末尾。 This means that if you input这意味着如果你输入

Test测试

Second Test第二次测试

Third Test第三次测试

The result after the first two inputs will be前两个输入后的结果将是

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

Your next value is supposed to go between those two, so the correct result becomes你的下一个值应该在这两者之间,所以正确的结果变成

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

but your code may only append to the strings right now.但您的代码现在可能只附加到字符串。 You also filter away strings that are not the shortest or the longst string inputed yet.您还可以过滤掉尚未输入的最短或最长字符串的字符串。 To solve this you have to implement some way to split the lists, and insertion of the value in the middle of the splitted values.要解决这个问题,您必须实现某种方法来拆分列表,并在拆分的值中间插入值。 This can be done in several ways for instance这可以通过多种方式完成,例如

The simplest way would be using Javas built-in List structure ie List<String> ascending = new ArrayList<>();最简单的方法是使用 Java 内置的 List 结构,即List<String> ascending = new ArrayList<>(); A possible solution to inserting the string in the correct position may then be将字符串插入正确位置的可能解决方案可能是

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

You may use the same loop but switch the comparision to be < instead to get an descending list.您可以使用相同的循环,但将比较切换为<以获取降序列表。

At the end you can print the values with最后,您可以打印值

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
*/

Use a linked list.使用链表。 Every time you add a word, look down your list one item at a time and insert your new node at position n, where n-1.length => n.length > n+1.length To read it backwards, you can either implement this as a doubly linked list, or read your singly linked list into a stack and pop off the stack每次添加单词时,一次查看列表中的一项,并在位置 n 插入新节点,其中 n-1.length => n.length > n+1.length 要向后阅读,您可以将其实现为双向链表,或将单链表读入堆栈并从堆栈中弹出

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

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