0

So I'm trying to sort a list of names both alphabetically and reverse alphabetically. The user would enter a list of names and once a blank entry is recorded, the program would sort the names and output it alphabetically and reverse alphabetically.

This is what I have so far:

import java.util.Scanner;

public class SortBuffer {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        System.out.println("Text Sorting Program: (ECSE 202 - Assignment 2)");
        System.out.println("Enter text to be sorted, line by line. A blank line terminates");
        System.out.println("You can cut and paste into this window");

        scan.nextLine();
        while (!scan.nextLine().isEmpty()) {
            scan.nextLine();
        }
        if (scan.nextLine().isEmpty()) {
            System.out.println("Text in sort order:");
        }
    }
}

UPDATE This is what I have now (but it has errors):

import java.util.ArrayList; import java.util.Scanner;

public class SortBuffer { public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    boolean moreLines = [];

    System.out.println("Text Sorting Program: (ECSE 202 - Assignment 2)");
    System.out.println("Enter text to be sorted, line by line. A blank line terminates");
    System.out.println("You can cut and paste into this window");


    List<String> scannedLines = new ArrayList<>();
    do{
        String scannedLine = scan.nextLine();
        boolean moreLines = !scannedLine.isEmpty();
        if (moreLines){
            scannedLines.add(scannedLine);
        }
        while (moreLines)

            java.util.Collections.sort(scannedLines);
    }




}}
  • 5
    Does this answer your question? [How can I sort a List alphabetically?](https://stackoverflow.com/questions/708698/how-can-i-sort-a-list-alphabetically) – Gideon Botha Feb 22 '21 at 21:11

1 Answers1

0

First you need to put all read lines in a list.

E.g.

List<String> scannedLines = new ArrayList<>();
boolean moreLines = false
do{
 String scannedLine = scan.nextLine();
 moreLines = !scannedLine.isEmpty();
 if (moreLines){
   scannedLines.add(scannedLine);
 }
} while (moreLines)

Then proceed like here: How can I sort a List alphabetically?

Joker
  • 2,304
  • 25
  • 36
  • Just try it and print it ;) There is a curly brace too much and you should initialize the boolean differently – Joker Feb 22 '21 at 22:17
  • It doesn't run: List cannot be resolved to a type Cannot infer type arguments for ArrayList<> Duplicate local variable moreLines Syntax error, insert "while ( Expression ) ;" to complete DoStatement – Math Geek 11 Feb 22 '21 at 22:33
  • Thank you! It's working now. I can accept inputs, sort, and output them in alphabetical order. How do I do it in reverse alphabetical order? – Math Geek 11 Feb 23 '21 at 02:07