The writefile method should write out to the given output file all the integers in the given array, one per line. For this part, the merge method should return a new array big enough to hold the content of the first two arrays (a and b), and then the first two copied into that array, without regard for order.

How would I do this?

Here is my code so far:

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

public class Merge1
{

    public static void main(String[] args)
    {

        File sorted1 = new File (args[0]);
        File sorted2 = new File (args[1]);
        File sortedout = new File (args[2]);
        Scanner input = new Scanner("sorted1.txt");
        readfile(input);

        /*for(int j = 0; j < sorted1; ++j)
        {
        int[] rock = new int[sorted1];
        System.out.println(rock[j]);

        } */
    } // end main

    static int[] readfile(Scanner input)
    {

        String num = "";
        while(input.hasNextInt())
        {
            num += input.nextInt() + " ";
        }
        String[] array = num.split(" ");
        int[] list = new int[array.length];
        for(int i = 0; i < array.length; i++)
        {
            list[i] = Integer.parseInt(array[i]);
        }
        return list;

    } // end readfile

    static void writefile(PrintStream output, int[] a)
    {



    } // end writefile

    static int[] merge(int[] a, int[] b)
    {
        int[] answer = new int[a.length + b.length];

        int i = 0;
        int j = 0;
        int k = 0;

        while (i < a.length && j < b.length)
        {
            if (a[i] < b[j])
            {       
                answer[k++] = a[i++];
            }

            else  
            {      
                answer[k++] = b[j++]; 
            }              
        }

        while (i < a.length)  
        {
            answer[k++] = a[i++];
        }


        while (j < b.length)
        {    
            answer[k++] = b[j++];
        }

        return answer;

    } // end merge 


} // end Merge1

Write file seems to be doing some ordering, despite the instructions.
Read file seems a bit convoluted. If you can assume that the file does just contain ints then you can read it as strings, split that, then convert to ints. Alternatively ( which I would prefer) create an int array of some sensible size, start reading ints into it directly. If it gets full copy to a larger array. At the end copy to an array of the exact correct size. Copying arrays of ints is very efficient, converting string to int to string to int less so.

This article has been dead for over six months. Start a new discussion instead.