2

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
LenglBoy
  • 1,451
  • 1
  • 10
  • 24
Dracose
  • 67
  • 8
  • 1
    Look here: https://stackoverflow.com/questions/4903611/java-list-sorting-is-there-a-way-to-keep-a-list-permantly-sorted-automatically –  Oct 11 '17 at 14:32

4 Answers4

1

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

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
jseashell
  • 745
  • 9
  • 19
1

Assuming you want to do stuff by your self, since this seems to be a practice assignment. Otherwise use j.seashell's answer.

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 i.e. 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);
}
Jotunacorn
  • 496
  • 1
  • 4
  • 12
0
/*
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
*/
0

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

Chris Phillips
  • 1,997
  • 2
  • 19
  • 34