Two simple array problems.
Hi, I'm new to Java and was wondering if anyone could help me with these two array problems.
1:
I have made this code that works to create multiplication tables with for loops:
Code:
public class MultiplyTables
{
public MultiplyTables()
{
}
public void printTable(int x, int y)
{
int [][] grid = null;
grid = new int [x+1][y+1];
for (int row = 1; row < grid.length; row++)
{
for (int col = 1; col < grid[row].length; col++)
{
grid[row][col] = row * col;
}
}
for (int row = 1; row < grid.length; row++)
{
for (int col = 1; col < grid[row].length; col++)
{
System.out.print(grid[row][col] + " \t");
}
System.out.println();
}
}
}
I'm trying to recreate this with while loops and have got the following which doesn't work:
Code:
public class MultiplyTables
{
public MultiplyTables()
{
}
public void printTable(int x, int y)
{
int [][] grid = null;
grid = new int [x+1][y+1];
int row = 1;
while (row < grid.length)
{
int col = 1;
while (col < grid[row].length)
{
grid[row][col] = row * col;
col++;
}
}
row++;
int row1 = 0;
while (row1 < grid.length)
{
int col1 = 1;
while (col1 < grid[row].length)
{
System.out.print(grid[row1][col1] + " \t");
col1++;
}
row++;
System.out.println();
}
}
}
Any ideas?
2. I have stored cubed numbers in an array and am trying to call up numbers from that array in the class methods but I am getting Null pointer errors even when I specifically ask for a value that should be there.
Code:
public class StoredCubes
{
private int j = 0;
int[] cubes;
private int numberOfCubes = 0;
public StoredCubes(int n)
{
numberOfCubes = n;
int[] cubes = new int[numberOfCubes];
for (int i=0; i<cubes.length; i++)
{
cubes[i] = j*j*j;
j = (j+1);
}
System.out.println(cubes[3]);
}
public void printOneCube(int k)
{
System.out.println(cubes[3]);
}
public void printMCubes(int m)
{
int i=0;
while(cubes[i] != m)
{
i++;
}
System.out.println(cubes[i]);
}
}
Any ideas with this? I'm guessing I'm not initialising the array properly and the cubes aren't being stored. The printing of the third value in the constructor is just there to show that it does work initially but the same code later brings up an error.
Thank you in advance.:confused: