Tyler
Tyler

Reputation: 7

How to sort Integers from Files

I am trying to take input from File1(.txt) and File2(.txt), combine and sort the Integers contained in both files and create a third File3(.txt), containing the sorted integers from files 1 and 2.

Here is my code so far:

    File input1 = new File("H:\\Desktop\\input1.txt");
    Scanner scan = new Scanner(input1);

    File input2 = new File("H:\\Desktop\\input2.txt");
    int num;

    while(scan.hasNextInt())
    {
        num = scan.nextInt();

        final List<Integer> list = Arrays.asList(num);
        Collections.sort(list);
        System.out.println(list);
    }

File1 contains numbers 10, 11, 8, 74, 16. Every array I try, I have always gotten Gibberish output, So I have resulted in this code. I get output but its not sorted:

[10]
[11]
[8]
[74]
[16]

Can anyone help and or give advice?

Upvotes: 1

Views: 1349

Answers (1)

Jimenemex
Jimenemex

Reputation: 3166

  1. Move your list outside the loop so it's not initialized every time. Also remove the final keyword since it will change in size.

  2. To add to a List<Integer> use .add(element);. This will add a new element to the end of the list.

  3. Repeat this logic for the second file.

  4. Call Collections.Sort(list); When you are done populating the list.

  5. Create the new file. Loop through the list and write the elements to the file

  6. Close the file

Check it out below. (I don't have a Java compiler atm so it might not work) Hopefully you get the idea.

File input1 = new File("H:\\Desktop\\input1.txt");
Scanner scan = new Scanner(input1);

File input2 = new File("H:\\Desktop\\input2.txt");
int num;
List<Integer> list = new ArrayList<Integer>();

while(scan.hasNextInt())
{
    num = scan.nextInt();
    list.add(num); 
}
scan = new Scanner(input2); // Point Scanner to new file    
while(scan.hasNextInt()) // Loop through new file
{
    num = scan.nextInt();
    list.add(num); 
}
Collections.sort(list); // sort list after populating it from both files

// Printing to file
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
for(int numberInList : list) { // Loop through sorted list and print out list to file
    writer.println(numberInList);
}
writer.close(); // Close the file

Upvotes: 1

Related Questions