Search code examples
javastringsortingarraylistbubble-sort

How to bubblesort/alphabetize(using .compareTo) a .txt file that the user enters? [Java]


Alright. I have spent hours trying to solve this but all I get is a plethora of errors. What I am trying to make is a program that allows for someone to enter a .txt file (this is not my issue) and to have it alphabetize itself by using some sort of a for-loop and then display itself to the user (I also don't know how to print my .txt file and show it to the user). This is my code (don't laugh, I know it is horrendous). I can code fairly well but for some reason this specific area is giving me loads of issues.

import java.util.Scanner;
import java.io.File;

public class AlphaSortingBubble {


  public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter file you want to alphabetize");
    String list = keyboard.nextLine();
    Scanner infile = null;
    try {
      infile = new Scanner(new File(list));
      System.out.println("File Found: " + list);
    } catch (Exception e) {
      System.out.println("Error: file not found");
      System.exit(0);
    }
    List < String > myList = new ArrayList < String > (Arrays.asList(list.split(",")));
    sortStringBubble(myList);
    for (int k = 0; k < 4; k++)
      System.out.println(myList[k]);
  }


  public static void sortStringBubble(String x[]) {
    int j;
    boolean flag = true; // will determine when the sort is finished
    String temp;

    while (flag) {
      flag = false;
      for (j = 0; j < x.length - 1; j++) {
        if (x[j].compareToIgnoreCase(x[j + 1]) > 0) { // ascending sort
          temp = x[j];
          x[j] = x[j + 1]; // swapping
          x[j + 1] = temp;
          flag = true;
        }
      }
    }
  }
}

Yeah, its pretty bad. I will be in debt to anyone that can help.


Solution

  • From your problem statement, I think you are looking to sort a single text file.

    However, looking at the statement: List < String > myList = new ArrayList < String > (Arrays.asList(list.split(",")));

    In the above statement, you are trying to create a list of all the comma separated strings that you entered in the console. Does it mean you are giving multiple file names separated by comma? If yes, you are not handling all the files in your code as seen from this statement:

    infile = new Scanner(new File(list));
    

    The above statement will only look for one file. So you have to check if you need a single file or multiple files and handle it accordingly. Lets say you only want to sort a single file, then, you need to parse the file and pass it into a String array because that is the syntax of sortStringBubble(String[] x)