Advertisement
ssunlimited

Sort A List of Strings

Apr 28th, 2024
1,015
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.28 KB | None | 0 0
  1. //This is a Java program.
  2. //It sorts the list of your things specified by name.
  3. //This code was written in the JGrasp compiler.
  4. //Have the text file in the same directory as this file.
  5. //The file that you input must exist and its name match
  6. //it with the format extension.
  7. //For example, if you have a text file
  8. //called "BookList," you must input it as BookList.txt.
  9. //In the file, each item must be written on each line like this:
  10.  
  11. //The Great Gatsby
  12. //A Streetcar Named Desire (without the double slashes [//])
  13.  
  14. import java.util.*;
  15. import java.io.*;
  16.  
  17. public class SortAListFromFile{
  18.    public static void main(String [] args){
  19.    List<String> media = new ArrayList<String>();
  20.    try{
  21.    Scanner console = new Scanner(System.in);
  22.    System.out.println("What is your text file to sort called?");
  23.    String fileName = console.nextLine();
  24.    Scanner textConsole = new Scanner(new File(fileName));
  25.    while(textConsole.hasNextLine()){media.add(textConsole.nextLine());};
  26.    console.close();
  27.    textConsole.close();
  28.    }
  29.    catch (FileNotFoundException e) {
  30.       System.out.println("An error occurred.");
  31.       e.printStackTrace();
  32.    }
  33.    Collections.sort(media);
  34.    System.out.println("The sorted order is: ");
  35.    for(var iterator : media) System.out.println(iterator);
  36.    }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement