Take numbers from a file and sort them

advertisements

I need to make my program read a file, then take the numbers in the string and sort them into an array. I can get my program to read the file and put it to a string, but that's where I'm stuck. All the numbers are on different lines in the file, but appear as one long number in the string. This is what I have so far:

public static void main(String[] args) {

    String ipt1;
    Scanner fileInput;
    File inFile = new File("input1.dat");

    try {
        fileInput = new Scanner(inFile);
        //Reads file contents
        while (fileInput.hasNext()) {
            ipt1 = fileInput.next();
            System.out.print(ipt1);
        }
        fileInput.close();
    }
    catch (FileNotFoundException e) {
        System.out.println(e);
    }
}


If your task is just to get input from some file and you're sure the file has integers, use an ArrayList.

Scanner fileInput;
ArrayList<Double>ipt1 = new ArrayList<Double>();
File inFile = new File("input1.dat");

try {
    fileInput = new Scanner(inFile);
    //Reads file contents
while (fileInput.hasNext()){
    ipt1.add(fileInput.nextDouble()); //Adds the next Double to the ArrayList
    System.out.print(ipt1.get(ipt1.size()-1)); //Prints out what you just got.
}
fileInput.close();

}
catch (FileNotFoundException e){
    System.out.println(e);
}

//Sorting time
//This uses the built-in Array sorting.
Arrays.sort(ipt1);

However, if you DO need to come up with a simple array in the end, but CAN use ArrayLists, you can add the following:

Double actualResult[] = new Double[ipt1.size()]; //Declare array
for(int i = 0; i < ipt1.size(); ++i){
    actualResult[i] = ipt1.get(i);
}