TizzyT

LanguageSort -TizzyT

Feb 25th, 2016
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.37 KB | None | 0 0
  1. package languagesort;
  2. import java.io.*;
  3. import java.util.*;
  4.  
  5. public class LanguageSort {
  6.     // Main method
  7.     public static void main(String[] args) throws Exception {
  8.         // reads the lines of txt from location
  9.         String[] Languages = readLines("unsorted.txt");
  10.         // display the lines that are in the string array
  11.         displaysLines(Languages);
  12.         // sorts the string array in ABD order
  13.         sortStringArray(Languages);
  14.         // displays the now sorted string array
  15.         displaysLines(Languages);
  16.         // writes the string array to a specified path
  17.         writeLines("tutorials.txt",Languages);
  18.     }
  19.     // Returns a string aray from a file at specified path
  20.     public static String[] readLines(String Path) throws Exception {
  21.         File unsortedLanguages = new File("unsorted.txt");
  22.         Scanner FileReader;
  23.         FileReader = new Scanner(unsortedLanguages);
  24.         String[] tempArray = new String[100];
  25.         int count = 0;
  26.         while (FileReader.hasNextLine()) {
  27.             tempArray[count] = FileReader.nextLine();
  28.             count++;
  29.         }
  30.         String[] lines = new String[count];
  31.         System.arraycopy(tempArray, 0, lines, 0, count);
  32.         FileReader.close();
  33.         return lines;
  34.     }
  35.     // Displays a string array line by line
  36.     public static void displaysLines(String[] lines) {
  37.         for (String line : lines) System.out.println(line);
  38.         System.out.println();
  39.     }
  40.     // Sorts the specified string array in ABC order (BubbleSort)
  41.     public static void sortStringArray(String[] lines) {
  42.         boolean swapped;
  43.         String temp;
  44.         do {
  45.             swapped = false;    
  46.             for(int i=0; i < (lines.length - 1) ; i++) {
  47.                 if(lines[i+1].compareTo(lines[i]) < 0) {
  48.                     temp = lines[i];  
  49.                     lines[i] = lines[i+1];
  50.                     lines[i+1] = temp;
  51.                     swapped = true;
  52.                 }
  53.             }
  54.         } while (swapped);
  55.     }
  56.     // Writes a string array to an output file, each element is a line
  57.     public static void writeLines(String Path, String[] lines) throws Exception {
  58.         File tutorials = new File(Path);
  59.         PrintWriter output;
  60.         output = new PrintWriter(tutorials);
  61.         for (String line: lines) output.println(line);
  62.         output.close();
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment