Reputation: 11
I was writing this program and I think I have everything write, but it pops up '.class' expected and I don't get why. Please help me. Thanks.
import java.util.*;
public class JoinArrays
{
public static void main(String[] args)
{
int[] x = { 5, 4, 3, 2, 1};
int[] y = { 8, 7, 6};
int[] z;
int i;
System.out.println("Original arrays:");
display(x);
display(y);
z = joinArrays(x, y);
System.out.println("Result of join(x,y).");
display(z);
}
private static void display( int[] x )
{
int i;
System.out.print("Array: ");
for(i=0; i < x.length; i++)
{
if( i < x.length-1 )
System.out.printf("%3d, ", x[i]);
else
System.out.printf("%3d\n", x[i]);
}
}
public static int[] joinArrays(int[] x, int[] y)
{
int i;
return int x[i] + int y[i];
}
}
Upvotes: 0
Views: 256
Reputation: 718698
The problem is that your joinArrays
method is not meaningful.
int x[i] + int y[i];
is not meaning full as an expression. x[i] + y[i]
would be syntactically valid ...
The variable i
is not initialized so x[i] + y[i]
wouldn't be allowed.
Even if x[i] + y[i]
was allowed, it is actually adding two integers ... to give an integer.
Basically, you are barking up the wrong tree here. Java does not have an operator (or any other form of syntax) for joining or concatenating arrays. You need to create a new array big enough to hold the elements of x
and y
and copy the elements of x
and y
to the new array; see @dicarlo2's Answer for an example.
May I suggest that you would do better reading a tutorial or a textbook on Java, rather than trying to learn Java by guessing what the syntax should be ...
Upvotes: 2
Reputation: 1418
Take a look at ArrayUtils.addAll() from Apache Commons, as suggested in here.
Upvotes: 0
Reputation: 1339
Try this:
package **YOUR PACKAGE NAME**;
import java.util.*;
public class **YOUR CLASS NAME** { public static void main(String[] args)
{
int[] x = { 5, 4, 3, 2, 1};
int[] y = { 8, 7, 6};
int[] z;
System.out.println("Original arrays:");
display(x);
display(y);
z = joinArrays(x, y);
System.out.println("Result of join(x,y).");
display(z);
}
private static void display( int[] x )
{
System.out.print("Array: ");
for(int i=0; i < x.length; i++)
{
if( i < x.length-1 )
System.out.printf("%3d, ", x[i]);
else
System.out.printf("%3d\n", x[i]);
}
}
public static int[] joinArrays(int[] x, int[] y)
{
int [] combination;
if(x.length < y.length)
combination = new int[x.length];
else
combination = new int[y.length];
for(int i = 0; i < x.length && i < y.length; i++)
combination[i] = x[i] + y[i];
return combination;
}
}
Upvotes: 0
Reputation: 4891
public static int[] joinArrays(int[] x, int[] y) {
int[] arr = new int[x.length + y.length];
System.arraycopy(x, 0, arr, 0, x.length);
System.arraycopy(y, 0, arr, x.length, y.length);
return arr;
}
Is what you want. See @StephenC's answer for reasons why your implementation does not work.
Upvotes: 1