I just wanna print my empty array by for loops.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
What is wrong?
int NYEARS = 5;
int NRATES = 3;
double[][] balancee = new double[NYEARS][NRATES];
for (int i = 0; i < NYEARS; i++) {
for (int j = 0; j < NRATES; j++) {
System.out.print(balance[NYEARS][NRATES] + " ");
System.out.println();
}
}
You should be using the loop indices to access the array elements, not the array dimensions:
for (int i = 0; i < NYEARS; i++) {
for (int j = 0; j < NRATES; j++) {
System.out.print(balance[i][j] + " ");
System.out.println();
}
}
I would prefer generally foreach when I don't need making arithmetic operations with their indices
for (double[] x : balancee) {
for (double y : x) {
System.out.print(y + " ");
}
System.out.println();
}
More importantly, I hope you get why you cannot use balance[NYEARS][NRATES].
Your solution will cause java.lang.ArrayIndexOutOfBoundsException: 5 you have also a typo balance instead you mean balancee:
So Instead you have to use balancee.length and balancee[i].length and not balance[NYEARS][NRATES], so you have to use balancee[i][j] like this :
for (int i = 0; i < balancee.length; i++) {
for (int j = 0; j < balancee[i].length; j++) {
System.out.print(balancee[i][j] + " ");
System.out.println();
}
}
Just use the built-in Arrays.deepToString()
int[][] foo = { null, {}, { 1 }, { 2, 3 } };
System.out.println(Arrays.deepToString(foo));
Output
[null, [], [1], [2, 3]]
int NYEARS = 5; //This is the size
int NRATES = 3; //This is the size
double[][] balancee = new double[NYEARS][NRATES]; //<-- balancee vs balance
for (int i = 0; i < NYEARS; i++) {
for (int j = 0; j < NRATES; j++) {
System.out.print(balance[NYEARS][NRATES] + " "); //<-- use i and j instead of size.
System.out.println();
}
}
Related
So I'm currently playing around with multidimensional arrays (2D) and I'm trying to reverse the order of each array in a 2-d array.
So I have a 2D-array set as:
int firstArray[][] = {{5,6,7,8,9,10}, {11,12,13,14,15,16}}
I have manually looked through the issue to see where I may have went wrong, to see which part of my code would end up going out of bounds in regards to my for-loops. The -1 part also caught me off guard.
I have began doing reverses on a regular 1-d array, and tried to apply the same concept to multidimensional arrays.
class Test2 {
public static void main (String[] args) {
int firstArray[][] = {{5,6,7,8,9,10}, {10,11, 12, 13, 14, 15}};
System.out.println("FIRST ARRAY");
display(firstArray);
}
public void display(int [][]num) {
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < num[i].length/2; j++) {
int temp = num[i][j];
num[i][j] = num[i][num.length-1-j];
num[i][num.length-1-j] = temp;
}
}
for (int a = 0; a < num.length; a++) {
for (int b = 0; b < num[a].length; b++) {
System.out.print(num[a][b] + "\t");
}
System.out.println();
}
}
}
I want the output using my display method to basically be a reverse of the arrays in my 2-d array:
10 9 8 7 6 5
15 14 13 12 11 10
The issue that I'm getting is an
Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException: -1
ArrayIndexOutOfBoundsException: -1
at Test2.display(Test2.java:30)
at Test2.main(Test2.java:20)
You are using the length of the wrong dimension.
With num.length you are using the number of rows and not the number of columns of the current row.
You need to change that to num[i].length.
public static void display(int [][]num) {
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < num[i].length/2; j++) {
int temp = num[i][j];
num[i][j] = num[i][num[i].length-1-j];
num[i][num[i].length-1-j] = temp;
}
}
for (int a = 0; a < num.length; a++) {
for (int b = 0; b < num[a].length; b++) {
System.out.print(num[a][b] + "\t");
}
System.out.println();
}
}
Notice you wrote num[i][num.length-1-j];
num.length-1-j is basically 2 - 1 -j.
public static void display(int [][]num) {
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < num[i].length/2 ; j++) {
int temp = num[i][j];
num[i][j] = num[i][num[i].length-1-j];
num[i][num[i].length-1-j] = temp;
}
}
for (int a = 0; a < num.length; a++) {
for (int b = 0; b < num[a].length; b++) {
System.out.print(num[a][b] + "\t");
}
System.out.println();
}
}
I've got the following code, I'm trying to get it to multiply array a by array b and produce array c. I've browsed several questions on here and for some reason I can't get the array to produce the correct results, I believe because it's not multiplying the right indices by one another. Any help would be greatly appreciated, as I am still trying to grasp how array multiplication works. Here is the code:
class Main
{
public static void main (String[] args)
{
int[][]a =
{
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
//print array a
};
for(int i = 0; i < a[0].length-1; i++)
{
for(int j = 0; j < a[0].length; j++)
{
System.out.print(a[i][j] + " ");
}
System.out.println();
}
int[][]b =
{
{-1,-2,-3},
{-4,-5,-6},
{-7,-8,-9},
{-10,-11,-12},
};
System.out.println();
//print array b
for(int i = 0; i < b.length; i++)
{
for(int j = 0; j < b.length-1; j++)
{
System.out.print(b[i][j] + " ");
}
System.out.println();
}
System.out.println();
int[][]c = new int[a.length][b[0].length];
if(b.length == a[0].length)
{
for(int i = 0; i < a.length; i++)
{
for (int j = 0; j < b[0].length; j++)
{
for (int k = 0; k < a[0].length; k++)
{
c[i][j] = a[i][k]*b[k][j];
}
}
}
}
else
{
System.out.println("Dimension requirements not satisfied for accurate calculation");
}
for(int i = 0; i < c.length; i++)
{
for(int j = 0; j < c.length; j++)
{
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}
Change c[i][j] = a[i][k]*b[k][j]; to c[i][j] += a[i][k]*b[k][j];
The answer by #Jeffrey Chen is correct because in the matrix multiplication each row of the first matrix multiply by each column of second matrix
In your case row 1 of matrix a is 1, 2, 3, 4
Column 1 of matrix b is -1, -4, -7, -10
So the answer is (1*-1)+(2*-4)+(3*-7)+(4*-10)
= -1-8-21-40 = -70
Then the first row of matrix a multiply by second column of matrix b
(1*-2)+(2*-5)+(3*-8)+(4*-11)
= -2-10-24-44 = -80
And so on
So the following is correct
c[i][j] += a[i][k] * b[k][j];
I have a 2-dimensional array in java.
For example,
double count=0;
double[][] arr1 =new double[3][3];
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
arr1[i][j]=count;
count++;
}
}
Now, I want to remove all elements where i or j value was 1.
arr1[1][0], arr1[1][1], arr1[1][2], arr[0][1], arr[2][1] ...
How can I achieve this?
Copies into arr2.
If you had
[1][2][3]
[4][5][6]
[7][8][9]
You'd get
[1][3]
[7][9]
If you wanted
[1][-][3]
[-][-][-]
[7][-][9]
See shijima's answer
double[][] arr2 = new double[arr1.length][arr1[0].length];
int ti = 0, tj = 0;
for(int i=0; i<arr1.length - 1; i++) {
if (i > 0)
ti = i+1;
else
ti = i;
for(int j=0; j<arr1[0].length - 1; j++) {
if (j > 0)
tj = j+1;
else
tj = j;
arr2[i][j] = arr1[ti][tj];
}
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(i==1 || j==1){
arr1[i][j]=0;
}
}
}
or with much better efficiency :
for(int i=0;i<3;i++){
arr1[i][1]=0;
}
for(int i=0;i<3;i++){
arr1[1][i]=0;
}
ArrayList would make your life a lot easier since you could just call remove(int), but if you insist on arrays you could do this.
double[] tmp = arr1[0];
arr1 = Arrays.copyOfRange(arr1, 1, arr1.length);
arr1[0] = tmp;
You could just avoid adding anything if i = 1, that way you don't need to worry about removing anything, since it will be empty later anyway...
double count = 0;
double[][] arr1 = new double[3][3];
outerLoop: for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1) {
continue outerLoop;
}
arr1[i][j] = count;
count++;
}
}
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
System.out.println("arr1[" + x + "][" + y + "]=" + arr1[x][y]);
}
}
I try to convert 1D to 2D array, but I keep getting java.lang.ArrayIndexOutOfBoundsException, and I have tried whatever I could find on the stackoverflow or internet, but I do not understand why I have this issue?
public class Arrayto2DArray {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int[] a = {0,1, 6, 83, 4, 5, 12, 7};
int[][] b = new int[4][4];
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[i].length; j++) {
b[i][j]=0;
System.out.print(b[i][j]);
}
System.out.println();
}
System.out.println("--------------------------");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < b[i].length; j++) {
try{
b[i][j] = a[i+j*4];
}catch(Exception e){
e.printStackTrace();
System.out.println(e);
}
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(b[i][j]);
}
System.out.println();
}
}
}
I kind of know why I get this error and it because of this line
b[i][j] = a[i+j*4];
but I cannot come up any formula better than this.
Consider the second for-loop
Lets say when i = 3 and j= 3
a[i+j*4] evaluates to a[15] which is out of the array
When you declare you 2-d array, you specified int[][] b = new int[4][];, meaning that the first inner for loop for (int j = 0; j < b[i].length; j++) should result in a NullPointerException since b[i].length has no predefined length. Before intering the inner for loop, you should define the size of each b[i] like b[i] = new int[somenumber]
In regards to convert the 1d loop to a 2d, you need to define the rule around spliting it into the 2-d array. Then accordingly the second for loop need modification
EDIT:You modified your code to have an int[4][4] array, which means you have 16 placeholders. Your 1-d array contain only 8 placeholders. It depends on how you want to sort the array, like it can be
b 0 1 2 3
0 0 1 6 83
1 4 5 12 7
2 0 0 0 0
3 0 0 0 0
or any other pattern
Assuming the length of 1-d array is 8 and the total index of 2-d array is 16, the following is more of a general solution:
public static void main(String[] args) {
// TODO code application logic here
int[] a = { 0, 1, 6, 83, 4, 5, 12, 7 };
int[][] b = new int[4][4];
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[i].length; j++) {
b[i][j] = 0;
System.out.print(b[i][j] + "\t");
}
System.out.println();
}
System.out.println("--------------------------");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < b[i].length; j++) {
try {
if ((j + i * 4) < a.length)
b[i][j] = a[j + i * 4];
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(b[i][j] + "\t");
}
System.out.println();
}
}
What is wrong is your 2D array is a 4*4, so that means for each index, there will be 4 elements i.e. say values. So there would be a total of 16 values, so you would need a 1D array with 16 elements for the above code to work. Right now you have only 8 values in your 1D array.
I think your code should change like this
public class Arrayto2DArray {
public static void main(String[] args) {
// TODO code application logic here
int[] a = {0,1, 6, 83, 4, 5, 12, 7};
int[][] b = new int[4][2];
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[i].length; j++) {
b[i][j]=0;
System.out.print(b[i][j]);
}
System.out.println();
}
System.out.println("--------------------------");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < b[i].length; j++) {
try{
b[i][j] = a[i+j*4];
}catch(Exception e){
e.printStackTrace();
System.out.println(e);
}
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(b[i][j]+" ");
}
System.out.println();
}
}
}
Your correct formula should be like.
int[] a = {0,1, 6, 83, 4, 5, 12, 7};
int[][] b = new int[4][2];
int k=0;
for (int i = 0; i < b.length; i++) { // Column of 2D array
for (int j = 0; j < b[0].length; j++) { // Row of 2D array
b[i][j]= a[k++];
System.out.println(b[i][j]);
}
}
Edit:
For general case, If your row is fixed at 4 but column is not fixed than your 2D conversion formula should be like below.
int col = a.length / 4;
int remainder = a.length % 4;
if (remainder > 0) {
col = col + 1; // Get the correct column size.
}
int[][] b = new int[4][col];
int k = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < col; j++) {
if (k < a.length) {
b[i][j] = a[k];
System.out.println(b[i][j]);
}
k++;
}
}
When I am trying to run this code it shows java.lang.ArrayIndexOutOfBoundsException Error. Please help me to fix this code.
import java.util.*;
class Example {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
Random r = new Random();
final int N, S;
System.out.print("Input No of Students : ");
N = input.nextInt();
System.out.print("No of Subject : ");
S = input.nextInt();
int[][] st = new int[N][S];
int[] stNo = new int[N];
int[] stMax = new int[N];
for (int i = 0; i < N; i++) {
stNo[i] = r.nextInt(10000);
for (int j = 0; j < S; j++) {
st[i][j] = r.nextInt(101);
}
}
// Find max Value of marks of a Student
for (int i = 0; i < N; i++) {
for (int j = 0; j < S; j++) {
if (st[i][j] > st[i][j + 1]) {
stMax[i] = st[i][j + 1];
}
}
}
// Display marks
// Dispaly Column names
System.out.print("stNo\t");
for (int i = 1; i < S + 1; i++) {
System.out.print("Sub " + i + "\t");
}
System.out.print("Max");
// Print Values
for (int i = 0; i < N; i++) {
System.out.print(stNo[i] + "\t");
for (int j = 0; j < S; j++) {
System.out.print(st[i][j] + "\t");
}
System.out.print(stMax[i]);
System.out.println();
}
}
}
The error is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: (here shows the input for "S")
at pack1.Example.main(Example.java:31)
As I am a new to coding I can not fix this. Please help me to fix this.
Thanks
An ArrayIndexOutOfBoundsException error means you exceed the boundaries of the array. In your case, st has S colomns and you tried to reach the S+1-th element (index S).
st[i][j + 1] => when j == S-1 (the end of the loop), you do an out of bounds.
Now, as your comment say, you're looking for the max value. Then the code should be:
stMax[i] = 0;
for (int j = 0; j < S; j++) {
if (st[i][j] > stMax[i]) {
stMax[i] = st[i][j];
}
}
What your code is doing is comparing the current value to the next one. And every time the next value is greater than the current one, you update stMax[i]. This does not make sense.
This line is causing the exception:
stMax[i] = st[i][j + 1];
You are iterating j to the end of the array, and always looking for the next element. So when j reaches the end of the array it is still looking for one more index, hence the outOfBoundsException.