This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 4 years ago.
I'm writing a program for class where we hard code matrices in a driver class and put the matrix operations in a matrix class. I'm running into an issue where I get the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
I'm pretty sure that it's the second for loop but I can't think of what range to do to refer to the columns of the hard coded matrix in the driver class.
row and col are both instantiated in the Matrix class and I fixed the j++ but it still gives the same error even when I'm doing a 1x2 multiplied by a 2x3, for example
public Matrix mult(Matrix m) {
// TODO: Multiply the two matrices, store the value
// in a new matrix and return that matrix
Matrix m5 = new Matrix(new int[row][col]);
for (int i = 0; i < row; i++) {
for (int j = 0; j < m.myMatrix[0].length; j++) {
for (int k = 0; k < col; k++) {
m5.myMatrix[i][j] += myMatrix[i][k] * m.myMatrix[k][j];
}
}
}
return m5;
}
I do not see that row and col are being instantiated anywhere, so I'm guessing that you are using member variables of the Matrix class. Your resulting matrix shouldn't be the same size as the original matrix unless they are both square matricies. For example, if you multiply a 4X2 matrix by a 2X3 matrix, it should result in a 4X3 matrix. Wikipedia provides an example of this.
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
I have been trying to fill my
int[][][] sudoku = new int[5][9][9];
array with
String[][] tmp = new String[21][21];
tmp[][] holds numbers like
005700020009600020
490060010140050030
For example this code works perfect and it gives me the number I want
System.out.println(Integer.valueOf(tmp[4][10]));
But this code
//sudoku1
b=0; c=0;
for (int i = 0; i < 6; i++) {
for (int j = 9; j < 18; j++) {
sudoku[1][b][c] = Integer.valueOf(tmp[i][j]);
c++;
}
b++;
}
throws "Index 9 out of bounds for length 9" error
You have c defined outside both loops, and added 1 each execution in the inner loop. The inner loop gets executed 6*9 times, so c can reach even the value 54, but it throws exception when it reaches 9 when trying to use sudoku[1][b][c], as the array indexes for the third element of the multiarray sudoku go from 0 to 8.
This question already has answers here:
ArrayIndexOutOfBoundsException on a initialized Vector
(1 answer)
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Initial size for the ArrayList
(17 answers)
Closed 4 years ago.
I've read the documentation and looked at scores of SO questions and still can't create a vector of vectors without running into the ArrayIndexOutofBounds exception. For some context, I am creating a matrix, where each slot contains a reference to an edge, representing a flight from a source to a destination . Following one SO response, I set up my vector as follows.
Iterator<Edge> iter = array.iterator();
private Vector<Vector<Edge>> matrix = new Vector<Vector<Edge>>(9);
for (int i=0;i<9;i++){
matrix.add(i,new Vector<Edge>(9));
}
while (iter.hasNext()) {
Edge e = iter.next();
int s = e.source; //row
int d = e.destination; //col
Vector<Edge> row = matrix.get(s);
int size = row.size();
row.add(d, e); // Array Out of Bounds Exception
}
I believe I have initialized my inner and outer vectors and don't understand why the size of the vector is still zero. Do I have to initialize all the elements to null before I can start putting and getting elements? I would really appreciate your help.
new Vector<Edge>(9) creates an empty Vector of capacity 9. Therefore, calling add(d,e) for such a Vector when d is not 0 will throw ArrayIndexOutOfBoundsException.
To initialize each row Vector with null values, use:
for (int i = 0; i < 9; i++) {
Vector<Edge> v = new Vector<>(9);
matrix.add(v);
for (int j = 0; j < 9; j++)
v.add(null);
}
Constructs an empty vector with the specified initial capacity and with its capacity increment equal to zero.
Parameters:
initialCapacity the initial capacity of the vector
Throws:
java.lang.IllegalArgumentException if the specified initial capacity is negative
public Vector(int initialCapacity) {
this(initialCapacity, 0);
}
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I asked yesterday for a solution for rotating an 2d array with n*m.
I get this link as answer: How do you rotate a two dimensional array?
I tryed my best and I thougt it works fine. And yes it works for an n*n array but if n and m are different I get an IndexOutOfBounds Error and I have no Idea why.
Here is my code:
public void rot90DegRight(){
//get Matrix
this.Matrix = getMatrix();
int rows = Matrix.length;
int cols = Matrix[0].length;
// create a mirror of current matrix
RGBColor[][] mirror = getMatrix();
// create a new matrix
for (int i = 0; i < rows; i++){
for (int j = 0; j < cols; j++){
Matrix[j][rows - i - 1] = mirror[i][j];
}
}
// replace cols count with rows count
int tmp = rows;
rows = cols;
cols = tmp;
}
Thank you a lot for helping.
Because, when you rotate a 2d array, the rows becomes columns and the columns becomes the row. Rotating in the same matrix is possible only if n==m.
If n!=m then you need to declare a new 2d array.
This question already has an answer here:
Java - Two-Dimensional Arrays - Plotting Points
(1 answer)
Closed 6 years ago.
I have an assignment for a JAVA class I am taking. We are discussing two-dimensional arrays, however on this particular assignment, I can not figure out how to return back specific points and set those points with a specific value. Here is the assignment:
Write a method called create2DArray that will fill, create, and return a 10 x 10 2d array with random numbers in the range of 1 to 100. Write a method called print2DArray that will print a 10 x 10 2D array in row column fashion. Write a method called createCoords that will search the 2D array looking for any value that is evenly divisible by 3. Once you have found a number you should log the row, column location. This means when your method finishes it should produce a list of coordinates that I can use to plot my graph. This method must also return the number of coordinates that are divisible by 3 so that I know how many points there are to plot. I am not particular as to how the coordinates are returned back as long as I get a list of the row, column locations. So, I will leave it to you to work out a mechanism for returning the values. To test that you have logged the coordinates create another function called fillLocations that will fill the locations in the array you have logged with -1. So, your program should flow in this order 1.create2DArray 2.print2DArray 3.createCoords 4.fillLocations 5.print2DArray
I understand and have completed create2DArray and print2DArray, but I can not figure out createCoords and fillLocations. Here is what I have so far, but it does not work and there are errors present:
public int createCoords(int row1, int col1){
int[][] coords = new int[row1][col1];
int[][] count = new int[0][0];
int co = 0;
for(int row = 0; row < 10; row++)
{
for(int col = 0; col < 10; col++)
{
if(coords[row][col] % 3 == 0)
co++;
return count[row][col];
}
}
return co;}
public int fillLocations(int[][] count){
int x = 0;
int y = 0;
for(int row = 0; row < 10; row++)
{
for(int col = 0; col < 10; col++)
{
if(count[row][col] % 3 == 0)
x = row;
y = col;
break;
}
}
return (x, y);}
I'm not going to write the code, but pretty much how I would go about doing this is:
I would have a separate 2d boolean array the same size as the 2d int array, auto filled with false. This would go in createCoords.
use nested for loop to cycle through all addresses of the 2d int array, and when i find a number that's divisible by three, i mark the corresponding point on the boolean array as 'true'. This would also go in createCoords.
after the for loops finish, I then look at the original 2d int array and boolean array. i would use the nested for loops again, and when i find a true value on the boolean array, i would mark the corresponding location on the int array as -1. This would go in fillLocations. You should also pass the 2d boolean array to fillLocation along with the 2d int array.
Good luck!
EDIT: this is assuming that the FillLocation function REPLACES values in the 10x10 int array with -1. That's what I interpreted your question to be. Please correct me if i'm wrong. I also added a short description at the end of each paragraph where each segment of code would go.
There are couple of problems with your code. Firstly, for the fillLocations method, you are expected to return the NUMBER of cells ([row][column]) where the value is divisible by 3. This means that for each value that passes the test:
if(coords[row][col] %3 === 0)
Then you should increment the counter by 1.
So for this part, your code would look like:
int [][] your2DArray = new int[10][10];
...
private int getNumberOfValuesDivisibleByThree(){
int numberOfValuesDivisibleByThree = 0;
for (int row=0; row < your2DArray.length; row++){
for(int col = 0; col < your2DArray[0].length; col++){
if(your2DArray[row][col] % 3 === 0){
//value at this coordinate or in this cell is divisible by 3
//here you can 'log' the coordinates as required -
System.out.println(row+","+col);
//increment the count
numberOfValuesDivisibleByThree +=1;
}
}
}
//return the final count
return numberOfValuesDivisibleByThree;
}
Please see how to create and manipulate a 2D array in Java. Syntax for creating a two-dimensional array
I have an assignment for a JAVA class I am taking. We are discussing two-dimensional arrays, however on this particular assignment, I can not figure out how to return back specific points and set those points with a specific value. Here is the assignment:
Write a method called create2DArray that will fill, create, and return
a 10 x 10 2d array with random numbers in the range of 1 to 100. Write
a method called print2DArray that will print a 10 x 10 2D array in row
column fashion. Write a method called createCoords that will search
the 2D array looking for any value that is evenly divisible by 3.
Once you have found a number you should log the row, column location.
This means when your method finishes it should produce a list of
coordinates that I can use to plot my graph. This method must also
return the number of coordinates that are divisible by 3 so that I
know how many points there are to plot. I am not particular as to how
the coordinates are returned back as long as I get a list of the row,
column locations. So, I will leave it to you to work out a mechanism
for returning the values. To test that you have logged the
coordinates create another function called fillLocations that will
fill the locations in the array you have logged with
-1. So, your program should flow in this order
create2DArray
print2DArray
createCoords
fillLocations
print2DArray
I understand and have completed create2DArray and print2DArray, but I can not figure out createCoords and fillLocations. Here is what I have so far, but it does not work and there are errors present:
public int createCoords(int row1, int col1){
int[][] coords = new int[row1][col1];
int[][] count = new int[0][0];
int co = 0;
for(int row = 0; row < 10; row++)
{
for(int col = 0; col < 10; col++)
{
if(coords[row][col] % 3 == 0)
co++;
return count[row][col];
}
}
return co;}
public int fillLocations(int[][] count){
int x = 0;
int y = 0;
for(int row = 0; row < 10; row++)
{
for(int col = 0; col < 10; col++)
{
if(count[row][col] % 3 == 0)
x = row;
y = col;
break;
}
}
return (x, y);}
As a programmer you'll nearly always need to research for doing different things. This research will be easier when you divide your problem to smaller problems.
For example you need to generate random numbers? So search on google that and you'll find this: How do I generate random integers within a specific range in Java?.
You need to create and return a 2D array? Google and see Syntax for creating a two-dimensional array
And with your art, put the pieces of the puzzle together in a way that gives your desired result.
public int[][] create2DArray() {
int[][] newArray = new int[10][10];
Random random = new Random();
int range = 100;
for(int i = 0; i < 10; i++)
{
for(int j = 0;j<arr[0].length;j++)
{
newArray[i][j]= (random.nextInt(range) + 1);
}
}
return newArray;
}
This method, creates and returns a 10*10 2D array filled with random generated numbers between 1-100. I'm sure you can write the rest of your program and enjoy from it by yourself.