Another question about java coding. I am getting a run time error. The program is to generate random numbers in two different arrays list each unsorted then sorted then merge the two sorted. I am getting the runtime error in the mergedArray method. Can anyone explain to me why this might be? Thank You
Code:
import java.util.*;
import java.io.*;
public class PGM2
{
public static void main(String[] args) throws IOException
{
String fname;
Scanner xyz = new Scanner(System.in);
System.out.println("Output filename? ");
fname = xyz.nextLine();
PrintWriter myOutputFile = new PrintWriter(fname);
int nums1 []; int nums2 []; int nums3 []; int sz1; int sz2;
System.out.print("What's the size of the first array? ");
sz1 = xyz.nextInt();
nums1 = new int[sz1];
fillArray(nums1);
System.out.println();
System.out.println("\n\nUnsorted Array #1: ");
writeNums(nums1, myOutputFile);
IntBubbleSorter.bubbleSort(nums1);
System.out.println();
System.out.println("\n\nSorted Array #1: ");
System.out.println();
writeNums(nums1, myOutputFile);
System.out.println();
System.out.println("What's the size of the second array? ");
sz2 = xyz.nextInt();
nums2 = new int[sz2];
fillArray(nums2);
System.out.println();
System.out.println("\n\nUnsorted Array #2: ");
writeNums(nums2, myOutputFile);
IntBubbleSorter.bubbleSort(nums2);
System.out.println();
System.out.println("\n\nSorted Array #2: ");
writeNums(nums2, myOutputFile);
nums3 = new int[sz1+sz2];
mergeArrays(nums1, nums2, nums3);
System.out.println("\n\nMerged Array: ");
System.out.println();
writeNums(nums3, myOutputFile);
myOutputFile.close();
}
public static void fillArray(int x[])
{
Random rd = new Random(System.currentTimeMillis());
for(int i = 0; i < x.length; i++)
x[i] = rd.nextInt(10000);
}
public static void writeNums(int x[], PrintWriter y)
{
for (int i = 0; i < x.length; i++)
{ System.out.printf("%8d", x[i]);
if (i%5 == 4)
System.out.println(); }
}
public static void mergeArrays(int x[], int y[], int z[])
{
int i=0; int j=0; int k=0; int index;
while(k < z.length)
if(x[i]==y[j])
{ z[k] = x[i]; z[k+1] = x[i]; i++; j++; k+=2; }
else
if(x[i] > y[j])
{ z[k] = y[j]; j++; k++; }
else
if(x[i] < y[j])
{ z[k] = x[i]; i++; k++; }
}
public static void bubbleSort(int[] array)
{
int maxElement;
int index;
int temp;
for (maxElement = array.length - 1; maxElement >= 0; maxElement--)
{
// The inner loop steps through the array, comparing
// each element with its neighbor. All of the elements
// from index 0 thrugh maxElement are involved in the
// comparison. If two elements are out of order, they
// are swapped.
for (index = 0; index <= maxElement - 1; index++)
{
// Compare an element with its neighbor.
if (array[index] > array[index + 1])
{
// Swap the two elements.
temp = array[index];
array[index] = array[index + 1];
array[index + 1] = temp;
}
}
}
}
}