Hi all, hope you can give me some help to edit my code. I'm unaware how to merge two arrays and allocate them to a third array(of the right size) and let's just say for the sake of things, we'll call it C. I went ahead and instead used the StringTokenizer, but I assume there's a simpler way to put it together.
(Also, I'm getting the data from a .txt file, for my instance the file is called "SortedArrays.txt")

import java.io.*;
import java.util.*;
class SortedArrays
{
    public static void main(String args[])throws FileNotFoundException{
        File f = new File("SortedArrays.txt");
        Scanner s =new Scanner(f);
        StringTokenizer h= new StringTokenizer(s.nextLine());
        int b=Integer.parseInt(h.nextToken());
        int[] ar1 = new int [b];
        int i;
        i=0;
        while(h.hasMoreTokens() && i<b){
            ar1[i]= Integer.parseInt(h.nextToken());
            i++;
        }
        h= new StringTokenizer(s.nextLine());
        int bb=Integer.parseInt(h.nextToken());
        int[] ar2 = new int [bb];
        i=0;
        while(h.hasMoreTokens() && i<bb){
            ar2[i]= Integer.parseInt(h.nextToken());
            i++;
        }
        s.close();
        i=0;
        System.out.print("ArrayA: ");
        while(i<ar1.length){
            System.out.print(ar1[i]+" ");
            i++;
        }
        i=0;
        System.out.print("\n");
        System.out.print("ArrayB: ");
        while(i<ar2.length){
            System.out.print(ar2[i]+" ");
            i++;
        }
        int[] ar3 = new int[ar1.length + ar2.length];
        int index = 0;
        for(i = 0;i < ar1.length;i++){
            ar3[index] = ar1[i];
            index++;
        }
        for(i = 0;i < ar2.length;i++){
            ar3[index] = ar2[i];
            index++;
        }
        Arrays.sort(ar3);
        i=0;
        System.out.print("\n");
        System.out.print("ArrayC: ");
        while(i<ar3.length){
            System.out.print(ar3[i]+" ");
            i++;
        }
    }
}

Basically, how can I re-edit/write this code without using StringTokenizer to allocate two arrays into a third? If anyone could show me how, it'd be extremely helpful. I tried my best to do it alone, but just reverted to using StringTokenizer. **yes this code is mine

Dani AI

Generated

A straightforward, robust approach is to read the two arrays with Scanner (or BufferedReader + split) and then perform a linear merge (the merge step from merge‑sort). That avoids concatenating then calling Arrays.sort and runs in O(n1+n2) time. Use Scanner.nextInt() to read counts and values (it ignores line breaks), then fill a third array by advancing two indexes and copying the smaller element each step.

// linear merge (assumes a and b are already sorted)
public static int[] mergeSorted(int[] a, int[] b) {
    int n = a.length, m = b.length, k = 0;
    int[] c = new int[n + m];
    int i = 0, j = 0;
    while (i < n && j < m) {
        if (a[i] <= b[j]) c[k++] = a[i++];
        else c[k++] = b[j++];
    }
    while (i < n) c[k++] = a[i++];
    while (j < m) c[k++] = b[j++];
    return c;
}

// read counts + values (file example: "3 1 3 5 4 2 4 6 8")
Scanner s = new Scanner(new File("SortedArrays.txt"));
int n = s.nextInt(); int[] a = new int[n]; for (int i=0;i<n;i++) a[i]=s.nextInt();
int m = s.nextInt(); int[] b = new int[m]; for (int i=0;i<m;i++) b[i]=s.nextInt();
s.close();
int[] c = mergeSorted(a,b);

Notes and pitfalls: confirm each input count matches the following numbers or use hasNextInt checks. If the two source arrays might not be sorted, call Arrays.sort on each before merging (or sort the combined array if simpler). For unknown sizes, read into ArrayList<Integer> then convert. Handle FileNotFoundException and InputMismatchException for malformed files.

Tiebacks: is right that combining then sorting is simple, but the linear merge is faster for already-sorted arrays. correctly separates input parsing from merging logic. ’s warning about StringTokenizer is apt—prefer Scanner or String.split for new code.

Recommended Answers

All 5 Replies

You could just combine the two arrays into a new array and then sort it. When you are going through both of you two orginal arrays, some kind of sorting comparison must be done to combine the two into the new sorted order. I don't know if this helps, but I would keep it simple.

Cool thanks for your feedback, I'll look into it.

You are NOT using StringTokenizer to merge the 2 arrays into the 3rd. You are using it to read the 2 arrays from a txt file. In that context, your strategy will depend on the way the data is distributed in that txt file.

As far as the merging is concerned, I believe you're looking into a better solution ^^

also: before making the choice to use StringTokenizer, read this line from the StringTokenizer api:

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

Okay great, thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.