Skip to content
Advertisement

Reading input from 2 files and writing to a third file in ascending order

I have 2 files that each contain a series of ordered numbers, separated by spaces (" ").

Write a program that produces a third file that will contain the ascending sequence of numbers. When solving, you are not allowed to use any type of collection.

File 1: 1 18 40 100 File 2: 0 10 15 80 1001

I managed to convert the number to String, but in the output file I’ve got the only 2 first numbers sorted : 0 1

JavaScript

Advertisement

Answer

Within your code you’re only reading and sorting the first two numbers from each file, simply because you’ve used the right method, nextInt(), only once per file (right before the while loop).

After that, you’re trying to “iterate” the rest of the files, but instead you’re only reading the rest of both files’ lines with the nextLine() method not their numbers. Besides, what you’re reading with the nextLine() is not even assigned to anything, discarding everything you’ve just read.

What you want to do is replacing those nextLine() with nextInt() and those hasNext() with hasNextInt(). Furthermore, a PrintWriter will be more helpful than just a basic FileWriter in writing the actual int value. You may find more about it in the documentation and here.

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement