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




}}
1

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

3 Comments

Just try it and print it ;) There is a curly brace too much and you should initialize the boolean differently
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
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.