Merge Sorting Alphabetically, worked with predetermined names earlier but not with command line files

StackOverflow https://stackoverflow.com/questions/22950778

  •  30-06-2023
  •  | 
  •  

문제

so I'm trying to write a program that sorts the contents of a file typed in from the command line alphabetically. I'm having troubles with reading in the file and then copying it from an arrayList "myArrayList" to an array "myList" to be printed in my "main" here's my code:

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

public class MergeSortLines {
public static void main(String[] args)
   throws FileNotFoundException {
    loadArray(args[0]) ;
}

public static String[] loadArray(String fileName)
   throws FileNotFoundException {
  String[] myList = null ;
  ArrayList<String> myArrayList = new ArrayList<String>();
  if ( (fileName != null) && (!fileName.equals("")) ) {
    Scanner input = new Scanner(new File(fileName)) ;
    while (input.hasNextLine()) {
        String a = input.nextLine();
        myArrayList.add(a);
    }
    myList = myArrayList.toArray(new String[] {});
    System.out.println(Arrays.toString(myList));

  }
 return myList ;
}


public static void mergeSort(String[] a) {
    if (a.length >= 2) {
        String[] left = new String[a.length / 2];
        String[] right = new String[a.length-a.length / 2];

        for (int i = 0; i < left.length; i++)
        {
            left[i] = a[i];
        }
        for (int i = 0; i < right.length; i++)
        {
            right[i] = a[i + a.length / 2];
        }

        mergeSort(left);
        mergeSort(right);

        merge(a, left, right);
    }
}

public static void merge(String[] result, String[] left, String[] right) {
    int i1 = 0;
    int i2 = 0;
    for (int i = 0; i < result.length; i++) {
        if (i2 >= right.length || (i1 < left.length &&
                             left[i1].compareToIgnoreCase(right[i2])<0)) {
                  result[i] = left[i1];
                  i1++;
             } else {
                  result[i] = right[i2];
                  i2++;
             }
        }
    }
}

it compiles correctly but I get a NoSuchElementException error code when I run it. My questions are, did I do the while loop correctly for the scanner? How do I utilize toArray() correctly? and finally, if I have the wrong idea, what is the correct way to copy the file to an array? Thanks I appreciate any help whatsoever! EDIT Thanks to HoverCraft Full of Eels, I got the contents of the file displaying properly, now it won't sort alphabetically when it worked with names I put in the code from when I started testing it! any ideas?

도움이 되었습니까?

해결책

To answer my own question, I neglected to call the methods to execute them so that the mergeSort would sort my list properly

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top