I am trying to concatenate two two-dimensional arrays of different sizes. I have no idea why my method doesn't work. Java tells me, when I mouse over the "return xx": "Type mismatch: cannot convert from int[][] to int[]". When I mouse over "concatenateArr2d..." I get: "Illegal modifier for parameter concatenateArr2d: only final is permitted".
I don't understand why I am getting this error.
public static int[][] concatenateArr2d(int[][] t, int[][] s)
{
int[][] xx = new int[t.length + s.length][];
for(i = 0; i < xx.length; i++)
{
xx[i] = new int[t[i].length + s[i].length];
}
return xx;
}
I still have to do the code to fill the entries but that should not be a problem.
Any help please? Thank you.
It looks to me that the code before the bit you pasted does not have aligned braces. You're probably inside a method when you try to declare this method.
public class HelloWorld{
public static int[][] concatenateArr2d(int[][] t, int[][] s)
{
int jLength=0;
// The below line of code is to determine second dimension size of new array
jLength=Math.max(s[0].length, t[0].length);
int sIterate=0;
//new array created using size of first+second array for First dimension and maximum size for second dimension
int[][] xx = new int[t.length + s.length][jLength];
//first array copy
for(int i = 0; i < t.length; i++)
{
for(int j = 0; j < t[0].length; j++)
{
xx[i][j] =t[i][j];
}
}
//second array copy
for(int i = t.length; i < xx.length; i++)
{
for(int j = 0; j < s[0].length; j++)
{
xx[i][j] =s[sIterate][j];
}
sIterate++;
}
return xx;
}
public static void main(String []args){
int a[][]={{1,2},{2,3},{1,1}};
int b[][]={{1,2,3},{2,3,4}};
int c[][]=HelloWorld.concatenateArr2d(a,b);
//Output iteration
for(int i = 0; i < c.length; i++)
{
for(int j = 0; j < c[0].length; j++)
{
System.out.print(c[i][j]);
}
System.out.println();
}
}
}
note : The blanks filled by 'primitive type default value' like, for int its 0.
Output :
120
230
110
123
234
Related
well I need to do the first constrctor and I was given in the method an array that i need to copy from.
the method is -
public Matrix(int[][] array)
what i tried is this :
public Matrix(int[][] array)
{
for(int i =0; i < array.length; i++ ) // running all over the rows
{
for ( int j=0; j < array[i].length; j++ ) // running all over the columns
{
_matrixArray[i][j]=array[i][j];
}
}
}
it says that im pointing to null? im trying to avoid alliasing so yeah, might need some help with this question please : )
You need to instantiate the array before adding elements to it. For example:
class Matrix {
private int[][] _matrixArray;
public Matrix(int[][] array)
{
this._matrixArray = new int[array.length][array[0].length];
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
{
this._matrixArray[i][j]=array[i][j];
}
}
}
}
You have to initialize matrix first. But note, the [][] means arrays of arrays, so in general case, different rows could have various coulmns amount.
public class Matrix {
private final int[][] matrix;
public Matrix(int[][] arr) {
matrix = new int[arr.length][];
for (int row = 0; row < arr.length; row++)
matrix[row] = Arrays.copyOf(arr[row], arr[row].length);
}
}
Want to write the diagonal of an 2-dimensional array (n*n Matrix) into an one-dimensional array.
1 2 3
4 5 6 => 1 5 9
7 8 9
public int[] getDiagonalFromArray(int[][] two_d_array){
int[] diagonal_array = new int[two_d_array[0].length];
int k=0;
for (int i = 0; i < two_d_array[0].length; i++) {
for (int j = 0; j < two_d_array[1].length; j++) {
for (int l = 0; l < two_d_array[0].length; l++) {
diagonal_array[k]=two_d_array[i][j];} //HERE SHOULD BE THE ERROR... HOW DO I CYCLE THROUGH THE 1dim "diagonal_array"?
}
}
return diagonal_array;
}
This method delivers wrong values.
This method of mine works, but just Prints the diagonale, instead of putting it into an 1dim array.
public void getDiagonal(int[][] two_d_array){
//int[] diagonal_array = new int[two_d_array[0].length];
for (int i = 0; i < two_d_array[0].length; i++) {
for (int j = 0; j < two_d_array[1].length; j++) {
if (i==j) System.out.print(two_d_array[i][j]+" ");
}
}
}
Where is the logical difference? I tried the if-clause on the first method, but it raises the "outofbound"-Exception.
Thanks in advance.
Why do you need more than one loop?
for (int i = 0; i < two_d_array[0].length; i++) {
diagonal_array[i]=two_d_array[i][i];
}
Seems to be enough to me.
If your matrix has the same width and height, this is a solution:
public int[] getDiagonal(int[][] two_d_array){
int[] diagonal_array = new int[two_d_array.length];
for (int i = 0; i < two_d_array.length; i++) {
diagonal_array[i] = two_d_array[i][i];
}
return diagonal_array;
Here, I consider principal diagonal elements to be the set of elements , where n & m are the number of rows and the number of columns (per row?) respectively.
Thus, the number of diagonal elements is never greater than min(numOfRows, numOfColumns).
And so, you can always try:
public int[] getDiagonalFromArray(int[][] 2DArray){
int[] diagonalArray = new int[Math.min(2DArray.length, 2DArray[0].length]);
int k=0;
for (int i = 0; i < 2DArray.length && k < diagonalArray.l length; ++i) {
for (int j = 0; j < 2DArray[i].length && k < diagonalArray.l length; ++j) {
if (i == j) {
diagonalArray[k++]=2DArray[i][j];
}
}
}
return diagonalArray;
}
Threw in some bounds checks for good measure.
Your input matrix must at be at least rectangular (square makes most sense), otherwise, the code will behave unreliably.
This is the same as #Andreas' answer, but I sacrifice performance and brevity here for the sake of understanding.
class RotateMat {
static Integer[] swap(int x, int y) {
int a=x;
int b=y;
a=a^b;
b=a^b;
a=a^b;
return new Integer[]{a,b};
}
static int[][] rotate(int[][] arr) {
assert arr.length == arr[0].length;
int m = arr.length;
for (int i=0; i<m;i++) {
for (int k=0; k<m;k++) {
//int[] temp_arr = swap(arr[i][k], arr[k][i]);
//arr[i][k] = temp_arr[0];
//arr[k][i] = temp_arr[1];
int temp = arr[i][k];
arr[i][k] = arr[k][i];
arr[k][i] = temp;
}
}
print(arr);
return arr;
}
static void print(int[][] arr) {
int n=arr[0].length;
int m=arr.length;
assert m==n;
//System.out.println(m + " " + n);
for (int i=0; i<m;i++) {
for (int j=0; j<n; j++) {
System.out.print(arr[i][j]);
}
System.out.println();
}
}
public static void main(String[] args) {
int arr[][] = { {1,2,3}, {4,5,6}, {7,8,9}};
print(arr);
arr = rotate(arr);
print(arr);
}
}
I am a C user and trying to practice more java programming. I understand pass by value in java and that is the reason I try to return rotated array from rotate() function and assign it again to arr variable.
I get the same array printed even after I rotate....What am I doing wrong here?
In your second for loop, you are using the wrong variable. Change this:
for (int i=0; i<m;i++) {
for (int k=0; k<m;k++) {
^
int temp = arr[i][k];
arr[i][k] = arr[k][i];
arr[k][i] = temp;
To this:
for (int i=0; i<m;i++) {
for (int k=i; k<m;k++) {
^
int temp = arr[i][k];
arr[i][k] = arr[k][i];
arr[k][i] = temp;
This will produce output:
123
456 < First print statement in main method
789
147
258 < Print statement inside rotate method
369
147
258 < Second print statement in main method
369
(Note: I added the spaces between the print statements)
As you originally start with k = 0, you actually rotate the whole way round (which can be seen if you add debugging print statements).
You are actually rotating it twice, since you inner loop in rotate method works through the entire length.
Try for (int k=0; k<i; k++) instead.
You need to swap elements beneath the diagonal with those that are above.
Hi I am trying to take two arrays and turn them into one 2 dimensional array. However, I keep getting an error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at test5.sum(test5.java:12)
at test5.main(test5.java:38)
Here is my code:
public class test5 {
int[][] final23;
public int[][] sum(int[] x, int[] y) {
final23 = new int[2][x.length];
for (int i = 0; i < final23[i].length; i++) {
final23[1][i] = x[i];
final23[2][i] = y[i];
}
return final23;
}
public void print() {
for (int i = 0; i < final23[i].length; i++) {
for (int j = 0; j < final23[i].length; j++) {
System.out.print(final23[i][j] + " ");
}
}
}
public static void main(String[] args) {
int l[] = { 7, 7, 3 };
int k[] = { 4, 6, 2 };
test5 X = new test5();
X.sum(k, l);
X.print();
}
}
I am not really sure what the problem is. Sorry if the question is dumb, I am new to coding!
The problem is:
final23 [2][i] = y[i];
Java arrays always start at 0. So final23 only has [0] and [1].
Any array with n elements can go from 0 to n-1.
There is also a second problem with your program. You have this loop in both sum and print methods:
for (int i = 0; i < final23[i].length; i++)
In sum method it should be
for (int i = 0; i < final23[0].length; i++)
And in print method
for (int i = 0; i < final23.length; i++)
Otherwise you'll get ArrayIndexOutOfBoundsException again.
Note that the program works correctly only if both input arrays have the same length. This might be ok for your purposes, but keep that in mind.
Try
for (int i = 0; i < final23[i].length; i++)
{
final23 [0][i] = x[i];
final23 [1][i] = y[i];
}
Remember, all arrays are 0 based, even n-dimensional ones.
First of all, Beginner here.
I'm using this code.
class MDArrays {
public static void main(String[] args) {
int[][] x;
int t=2;
x = new int[2][3];
for(int i=0; i<=1; i++) {
for(int j=0; i<=2; j++) {
x[i][j] = t;
t += 2;
System.out.println(x[i][j]);
}
}
}
}
It compiles perfectly, but when running it, after displaying 3 numbers correctly I'm getting the following error.
Exception in thread "main" java.Lang.ArrayindexOutOfBoundsException : 3 at MDArrays.main(MDArrays.java:13)
Where am I going wrong?
You are incrementing j while checking against i.
for(int j=0; i<=2; j++)
j will keep incrementing which will eventually give you an IndexOutOfBoundsException
for(int j=0; i<=2; j++) {
Is your problem. Try:
for(int j=0; j<=2; j++) {
I would write it like this:
class MDArrays
{
private static final int ROWS;
private static final int COLS;
private static final int START_VALUE;
private static final int INC_VALUE;
static
{
ROWS = 2;
COLS = 3;
START_VALUE = 2;
INC_VALUE = 2;
}
public static void main(String[] args)
{
final int[][] x;
int t;
x = new int[ROWS][COLS];
t = START_VALUE;
for(int row = 0; row < x.length; row++)
{
for(int col = 0; col < x[row].length; col++)
{
x[row][col] = t;
t += INC_VALUE;
System.out.println(x[row][col]);
}
}
}
}
The major difference is that I use the .length member rather than hard coded values. That way if I change it to x = new int[3][2]; then the code magically works and stays within its bounds.
The other big difference is that I use row/col instead of i/j. i/j are fine (and traditional) but I find when dealing with arrays of arrays (Java doesn't actually have multi-dimensional arrays) that it is easier to keep track of things if I use the more meaningful row/col (helps prevent you from doing things like for(int col = 0; row < x.length; col++)... which, incidentally, is the bug you have.