Null Pointer Exception Error in a DoubleMatrix class [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'm having trouble with a java problem. I get this error:
Exception in thread "main" java.lang.NullPointerException
at DoubleMatrix.getDim1Size(DoubleMatrix.java:28)
at Program3.main(Program3.java:16)
I don't understand where it is null
public class DoubleMatrix
{
private double[][] doubMatrix;
public DoubleMatrix(int firstDim, int secondDim, double upperLimit)
{
if(firstDim > 0 && secondDim > 0 && upperLimit > 0){
firstDim = 1;
secondDim = 1;
upperLimit = 1;
}
}
public DoubleMatrix(double[][] tempArray)
{
if(tempArray != null && tempArray.length != 0){
for(int i =0; i < tempArray.length; i++) {
doubMatrix = tempArray;
}
}
else{
tempArray = new double[1][1];
}
}
public int getDim1Size(){
int firstDim1 = doubMatrix.length;
return firstDim1;
}
public int getDim2Size(){
int secondDim1 = doubMatrix[0].length;
return secondDim1;
}
private void makeDoubMatrix(int firstDim, int secondDim, double upperLimit){
double[][] randomMatrix = new double[firstDim][secondDim];
for(int row = 0; row < doubMatrix.length; row++) {
for(int column = 0; column < doubMatrix[row].length; column++){
doubMatrix[row][column] = (double)(Math.random() * 100);
}
}
}
public DoubleMatrix addMatrix(DoubleMatrix arrayObj)
{
if(doubMatrix.length == arrayObj.doubMatrix.length && doubMatrix[0].length == arrayObj.doubMatrix[0].length){
double[][] TotalTwoDimArray = new double[doubMatrix.length][doubMatrix[0].length];
for(int row = 0; row < TotalTwoDimArray.length; row++){
for(int column = 0; column < TotalTwoDimArray[row].length; column++){
TotalTwoDimArray[row][column] = doubMatrix[row][column] + arrayObj.doubMatrix[row][column];
}
}
return new DoubleMatrix(TotalTwoDimArray);
}
return new DoubleMatrix(1, 1, 1);
}
public DoubleMatrix getTransposedMatrix(){
double[][] TransMatrix = new double[doubMatrix[0].length][doubMatrix.length];
for(int row = 0; row < doubMatrix.length; row++){
for(int column = 0; column < doubMatrix[row].length; column++){
TransMatrix[row][column] = doubMatrix[column][row];
}
}
return new DoubleMatrix(TransMatrix);
}
public DoubleMatrix multiplyMatrix(DoubleMatrix obj1)
{
if(doubMatrix[0].length == obj1.doubMatrix.length){
double[][] multipliedMatrix = new double[doubMatrix.length][obj1.doubMatrix[0].length];
for(int i = 0; i < multipliedMatrix.length; i++){
for(int j = 0; j < multipliedMatrix[i].length; j++){
for(int k = 0; k < doubMatrix[0].length; k++){
multipliedMatrix[i][j] = doubMatrix[i][k] * obj1.doubMatrix[k][j] + multipliedMatrix[i][j];
}
}
}
return new DoubleMatrix(multipliedMatrix);
}
return new DoubleMatrix(1, 1, 1);
}
public void printMatrix(String titles){
System.out.println(titles);
for(int row = 0; row < doubMatrix.length; row++){
for(int column = 0; column < doubMatrix[row].length; column++){
System.out.printf("%9.1f", doubMatrix[row][column]);
}
System.out.println();
}
}
}
// main in different class
public class Program3
{
public static void main(String[] args)
{
DoubleMatrix doubMatObj1;
DoubleMatrix doubMatObj2;
DoubleMatrix doubMatObj3;
int max = 10;
int min = 3;
int firstDim = (int)(Math.random() * (max - min + 1) + min);
int secondDim = (int)(Math.random() * (max - min + 1) + min);
doubMatObj1 = new DoubleMatrix(firstDim, secondDim, 100.);
doubMatObj2 = new DoubleMatrix(doubMatObj1.getDim1Size(), doubMatObj1.getDim2Size(), 100.);
doubMatObj3 = doubMatObj1.addMatrix(doubMatObj2);
doubMatObj1.printMatrix("First Matrix Object");
doubMatObj2.printMatrix("Second Matrix Object");
doubMatObj3.printMatrix("Result of Adding Matrix Objects");
doubMatObj2.printMatrix("Result of Transposing Matrix Object");
doubMatObj1.multiplyMatrix(doubMatObj2);
doubMatObj3.printMatrix("Result of Multiplying Matrix Objects");
}
}

In java, non primitives don't get initialized by just declaring them. So if you get a NullPointerException in a line like foo.bar(), you know that foo had to be null. In your case you have doubMatrix.length, which indicates that doubMatrix has never been initialized. Looking at your code, only the second constructor ever initializes that variable, so calling the first constructor will leave doubMatrix==null to always be true.
I hope that is enough info to help you fix your problem yourself (and similar problems in the future), but I am not going to post a working code example, since fixing your code yourself will be a good exercise!
On a sidenote, in your second constructor you have:
for(int i =0; i < tempArray.length; i++) {
doubMatrix = tempArray;
}
If tempArray.length is for example 5, you would assign the same value 5 times to the same variable. I don't know what you are trying to do there, but it is certainly not what you had in mind.

Related

Construction of a class in java

I should carry out this exercise in the creation of a class, I uploaded this is the professor's solution, in sum and product methods can not quite figure out what place and why use "A".
class Vettore {
private int[] V = new int[6];
public Vettore(int[] X) {
if (X.length != 6)
throw new BadDataException();
for (int i = 0; i < 6; i++)
if (X[i] < 0)
throw new BadDataException();
else
V[i] = X[i];
}
public Vettore() {}
public Vettore somma(Vettore X) {
int[] A = new int[6];
for (int i = 0; i < 6; i++)
A[i] = V[i] + X.V[i];
return new Vettore(A);
}
public Vettore prodotto(Vettore X) {
int k = 0;
for (int i = 0; i < 6; i++)
k += V[i] * X.V[i];
return k;
}
public int get(int i) {
if (i < 0 || i > 5)
throw new BadDataException();
return V[i];
}
public String toString() {
String t = "( ";
for (int i = 0; i < 6; i++)
t += V[i] + (i == 5 ? " " : ", ");
return t + ")";
}
public boolean equals(Vettore X) {
for (int i = 0; i < 6; i++)
if (V[i] != X.V[i])
return false;
return true;
}
}
As far as I see it, and assuming somma means sum and prodotto means product, The A is needed because you have to store the sum values of the V and X.V arrays for every index. If you didn't use another array for this, you wouldn't be able to achive adding the appropriate indexes in somma for example. This method stands for - as I see it - Adding the two arrays' appropriate elements.
EDIT: another thing. Are you sure that the return types match variables to return? I elaborated the use of somma but didn't pay attention that prodotto has a wrong return type, just as it was said in the comments.
You might want to correct the prodotto method definition as -
public Vettore prodotto(Vettore X) {
int[] K = new int[6]; // deault values are 0
for (int i = 0; i < 6; i++)
K[i] += V[i] * X.V[i];
return new Vettore(K);
}
This would evaluate the product of the array field V for two instances of class Vettore namingly X the input param and the current instance that you would call the method from.
return new Vettore(K); creates a new instance of Vettore class with K as arrays field, while executing the constructor logic in place as follows -
public SumAndProductExercise(int[] X) {
if (X.length != 6) { // length of the array is 6 or not
throw new BadDataException();
}
for (int i = 0; i < 6; i++) {
if (X[i] < 0) { // all the elements of array are >=0 or not
throw new BadDataException();
} else {
V[i] = X[i]; // the field on the new instance
}
}
}

Find smallest number K , if exists, such that product of its digits is N. Eg:when N = 6, smallest number is k=16(1*6=6) and not k=23(2*3=6)

I have made this program using array concept in java. I am getting Exception as ArrayIndexOutOfBound while trying to generate product.
I made the function generateFNos(int max) to generate factors of the given number. For example a number 6 will have factors 1,2,3,6. Now,i tried to combine the first and the last digit so that the product becomes equal to 6.
I have not used the logic of finding the smallest number in that array right now. I will do it later.
Question is Why i am getting Exception as ArrayIndexOutOfBound? [i couldn't figure out]
Below is my code
public class SmallestNoProduct {
public static void generateFNos(int max) {
int ar[] = new int[max];
int k = 0;
for (int i = 1; i <= max; i++) {
if (max % i == 0) {
ar[k] = i;
k++;
}
}
smallestNoProduct(ar);
}
public static void smallestNoProduct(int x[]) {
int j[] = new int[x.length];
int p = x.length;
for (int d = 0; d < p / 2;) {
String t = x[d++] + "" + x[p--];
int i = Integer.parseInt(t);
j[d] = i;
}
for (int u = 0; u < j.length; u++) {
System.out.println(j[u]);
}
}
public static void main(String s[]) {
generateFNos(6);
}
}
****OutputShown****
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at SmallestNoProduct.smallestNoProduct(SmallestNoProduct.java:36)
at SmallestNoProduct.generateFNos(SmallestNoProduct.java:27)
at SmallestNoProduct.main(SmallestNoProduct.java:52)
#Edit
The improved Code using array only.
public class SmallestNoProduct {
public static void generateFNos(int max) {
int s = 0;
int ar[] = new int[max];
int k = 0;
for (int i = 1; i <= max; i++) {
if (max % i == 0) {
ar[k] = i;
k++;
s++;
}
}
for (int g = 0; g < s; g++) {
System.out.println(ar[g]);
}
smallestNoProduct(ar, s);
}
public static void smallestNoProduct(int x[], int s) {
int j[] = new int[x.length];
int p = s - 1;
for (int d = 0; d < p;) {
String t = x[d++] + "" + x[p--];
System.out.println(t);
int i = Integer.parseInt(t);
j[d] = i;
}
/*for (int u = 0; u < j.length; u++) {
System.out.println(j[u]);
}*/
}
public static void main(String s[]) {
generateFNos(6);
}
}
Maybe it better:
public class SmallestNoProduct {
public static int smallest(int n) {
int small = n*n;
for(int i = 1; i < Math.sqrt(n); i++) {
if(n%i == 0) {
int temp = Integer.parseInt(""+i+""+n/i);
int temp2 = Integer.parseInt(""+n/i+""+i);
temp = temp2 < temp? temp2: temp;
if(temp < small) {
small = temp;
}
}
}
return small;
}
public static void main(String[] args) {
System.out.println(smallest(6)); //6
System.out.println(smallest(10)); //25
System.out.println(smallest(100)); //205
}
}
Problem lies in this line
String t=x[d++]+""+x[p--];
x[p--] will try to fetch 7th position value, as p is length of array x i.e. 6 which results in ArrayIndexOutOfBound exception. Array index starts from 0, so max position is 5 and not 6.
You can refer this question regarding postfix expression.
Note: I haven't checked your logic, this answer is only to point out the cause of exception.
We are unnecessarily using array here...
below method should work....
public int getSmallerMultiplier(int n)
{
if(n >0 && n <10) // if n is 6
return (1*10+n); // it will be always (1*10+6) - we cannot find smallest number than this
else
{
int number =10;
while(true)
{
//loop throuogh the digits of n and check for their multiplication
number++;
}
}
}
int num = n;
for(i=9;i>1;i--)
{
while(n%d==0)
{
n=n/d;
arr[i++] = d;
}
}
if(num<=9)
arr[i++] = 1;
//printing array in reverse order;
for(j=i-1;j>=0;j--)
system.out.println(arr[j]);

How to compare integer elements within ArrayList?

I am trying to solve a problem by fetching the maximum number from each row in a triangle. So far am able to generate a triangle but how do I fetch the max number from each row?
Here is my code
private static Integer solve(Triangle triangle)
{
//triangle is extending an ArrayList
System.out.println(triangle);
return 0;
}
This is what am producing so far:
6
3 5
9 7 1
4 6 8 4
but now I want to get the result which says:
"In this triangle the maximum total is: 6 + 5 + 9 + 8 = 26"
Here is the complete code:
public class HellTriangle {
private static final int TRIANGLE_HEIGHT = 10;
public static void start() {
Triangle triangle = generateTriangle();
//System.out.println(triangle);
long start = System.currentTimeMillis();
Integer result = solve(triangle);
long end = System.currentTimeMillis();
System.out.println("Result:" + result);
System.out.println("Resolution time: " + (end - start) + "ms");
}
private static Triangle generateTriangle() {
Triangle triangle = new Triangle();
Random random = new Random();
for (int i = 0; i < TRIANGLE_HEIGHT; i++) {
Row row = new Row();
for (int j = 0; j <= i; j++) {
row.add(random.nextInt(100));
}
triangle.add(row);
}
return triangle;
}
private static class Row extends ArrayList<Integer> {
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++) {
sb.append(String.format("%02d", get(i)));
//rows.add(get(i));
if (i < (size() - 1)) {
sb.append(" ");
}
}
return sb.toString();
}
}
private static class Triangle extends ArrayList<Row> {
public String toString() {
// sb is used to make modification to the String
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++) {
for (int j = 0; j < (TRIANGLE_HEIGHT - 1 - i); j++) {
sb.append(" ");
}
sb.append(get(i));
if (i < (size() - 1)) {
sb.append("\n");
}
}
return sb.toString();
}
}
private static Integer solve(Triangle triangle) {
System.out.println(triangle);
return 0;
}
public static void main(String[] args) {
start();
}
}
Any help would be appreciated!
Here, just change with your solve()
private static void solve(Triangle triangle) {
System.out.println(triangle);
ArrayList<Integer> result = new ArrayList<Integer>();
int total = 0;
for(Row row : triangle){
Collections.sort(row);
total += row.get(row.size()-1);
result.add(row.get(row.size()-1));
}
for(Integer intr : result)
System.out.println("Largest elements of the rows: " + intr);
System.out.println("Total: " + total);
}
As there is no ordering in your rows and this would lead to O(n) to get the maximum value per row i would look up the maximum value during insertion. Something like that (not tested and you probably have to override the other add methods also, depending on your use case):
public class Row extends ArrayList<Integer> {
public String toString() {
...
}
private Integer max = null;
#Override
public boolean add(Integer elem) {
if (elem != null && (max == null || max < elem)) {
max = elem;
}
return super.add(elem);
}
public Integer getMax() {
return max;
}
}
Try
private static int getTriangleMax(final Triangle rows)
{
int max = 0;
for (final Row row : rows)
{
final int rowMax = getRowMax(row);
max += rowMax;
}
return max;
}
private static int getRowMax(final Row row)
{
int rowMax = Integer.MIN_VALUE;
for (final Integer integer : row)
{
if (rowMax < integer)
{
rowMax = integer;
}
}
return rowMax;
}
Simple-Solution:
1.Add the static list as here:
private static List maxRowVal=new ArrayList();
2.Replace your generateTriangle() function with this:
private static Triangle generateTriangle()
{
Triangle triangle = new Triangle();
Random random = new Random();
for (int i = 0; i < TRIANGLE_HEIGHT; i++) {
Row row = new Row();
int maxTemp=0;
for (int j = 0; j <= i; j++) {
int rand=random.nextInt(100);
row.add(rand);
if(rand>maxTemp)
maxTemp=rand; //will get max value for the row
}
maxRowVal.add(maxTemp);
triangle.add(row);
}
return triangle;
}
Simple indeed!!
This is not exactly what you asked for, but I would like to show you a different way to go about this problem. People have done this for me before, and I really appreciated seeing different ways to solve a problems. Good luck with your coding!
Below is the code in its entirety, so you can just copy, paste and run it.
public class SSCCE {
public static void main(String[] args) {
// Here you specify the size of your triangle. Change the number dim to
// whatever you want. The triangle will be represented by a 2d-array.
final int dim = 5;
int[][] triangle = new int[dim][dim];
// Walks through the triangle and fills it with random numbers from 1-9.
for (int r = 0; r < dim; r++) {
for (int c = 0; c < r + 1; c++) {
triangle[r][c] = (int) (9 * Math.random()) + 1;
}
}
// This piece just prints the triangle so you can see what's in it.
for (int r = 0; r < dim; r++) {
for (int c = 0; c < r + 1; c++) {
System.out.print(triangle[r][c] + " ");
}
System.out.println();
}
// This part finds the maximum of each row. It prints each rows maximum
// as well as the sum of all the maximums at the end.
int sum = 0;
System.out.print("\nIn this triangle the maximum total is: ");
for (int r = 0; r < dim; r++) {
int currentMax = 0;
for (int c = 0; c < r + 1; c++) {
if (triangle[r][c] > currentMax) {
currentMax = triangle[r][c];
}
}
sum += currentMax;
if (r != 0) {
System.out.print(" + ");
}
System.out.print(currentMax);
}
System.out.println(" = " + sum + ".");
}
}
Output:
9
9 2
1 7 3
1 7 3 3
5 7 5 1 9
In this triangle the maximum total is: 9 + 9 + 7 + 7 + 9 = 41.

Random generator does not work

i tried to implement a method to set up a board with an array of Cell object. the method then randomly place a new string "C10" over the "---" string. My class and main is below
public class Cell {
public int addSpaces;
public Cell() {
addSpaces = 0;
}
public Cell(int x) {
addSpaces = x;
}
public String toString() {
String print;
if (addSpaces == -10)
print = "C10";
else
print = "---";
return print;
}
}
import java.util.Random;
public class ChutesAndLadders {
Cell[] board = new Cell[100]; // Set array of Cell object
Random ran = new Random();
Cell s = new Cell();
public int Chut, Ladd;
public ChutesAndLadders() {
}
public ChutesAndLadders(int numChutes, int numLadders) {
Chut = numChutes;
Ladd = numLadders;
}
public void setBoard() {
for (int i = 0; i < board.length; i++)
board[i] = new Cell(); // board now has 100 Cell with toString "---"
for (int k = 1; k <= Chut; k++) {
int RanNum = ran.nextInt(board.length); // Randomly replace the
// toString
if (board[RanNum] == board[k])
this.board[RanNum] = new Cell(-10);
else
k--;
}
}
public void printBoard() { // method to print out board
int count = 0;
for (int i = 0; i < board.length; i++) {
count++;
System.out.print("|" + board[i]);
if (count == 10) {
System.out.print("|");
System.out.println();
count = 0;
}
}
}
public static void main(String[] args) {
ChutesAndLadders cl = new ChutesAndLadders(10, 10);
cl.setBoard();
cl.printBoard();
}
}
Instead of randomly placing C10 all over the board I got this output;
|---|C10|C10|C10|C10|C10|C10|C10|C10|C10|
|C10|---|---|---|---|---|---|---|---|---|
|---|---|---|---|---|---|---|---|---|---|
|---|---|---|---|---|---|---|---|---|---|
|---|---|---|---|---|---|---|---|---|---|
|---|---|---|---|---|---|---|---|---|---|
|---|---|---|---|---|---|---|---|---|---|
|---|---|---|---|---|---|---|---|---|---|
|---|---|---|---|---|---|---|---|---|---|
|---|---|---|---|---|---|---|---|---|---|
can someone tell me what i did wrong? Thank you.
I'm not sure what your intention with this was in your for-loop:
if (board[RanNum] == board[k])
But it will cause your for-loop to, for each k, generate random numbers until it generates k, and then set that cell. So for k == 1, it will always set cell 1, cell 2 for k == 2, cell 3 for k == 3, etc.
I'm guessing you want to do something more like:
for (int k = 1; k <= Chut; k++) {
int RanNum = ran.nextInt(board.length);
if (board[RanNum].addSpaces == 0) // uninitialized
this.board[RanNum] = new Cell(-10);
else
k--;
}
EDIT:
As you probably realized from the comment + other answers, the above code is not particularly readable. Something like this should be better:
int chutCount = 0;
while (chutCount < Chut)
{
int randomNum = ran.nextInt(board.length);
if (board[randomNum].addSpaces == 0) // uninitialized
{
board[randomNum] = new Cell(-10);
chutCount++;
}
}
I'm not sure exactly what you want to achieve, but if you eliminate the if else in your inner setBoard loop then you should get random placement of C10.
Change this:
for (int k = 1; k <= Chut; k++) {
int RanNum = ran.nextInt(board.length); // Randomly replace the
// toString
if (board[RanNum] == board[k])
this.board[RanNum] = new Cell(-10);
else
k--;
}
To this:
for (int k = 1; k <= Chut; k++) {
int RanNum = ran.nextInt(board.length); // Randomly replace the
// toString
this.board[RanNum] = new Cell(-10);
}
I think you meant !=.
for (int k = 1; k <= Chut; k++) {
int ranNum = (int)(Math.random()*board.length);
if (board[ranNum] != board[k])
this.board[ranNum] = new Cell(-10);
else
k--;
}

2D array Null Pointer Exception error

public class DoubleMatrix
{
private double[][] doubMatrix;
public DoubleMatrix(int row, int col)
{
if(row > 0 && col > 0)
{
makeDoubMatrix(row,col);
}
else
{
row = 1;
col = 1;
}
}
public DoubleMatrix(double[][] tempArray)
{
if(tempArray != null)
{
for(int i = 0; i < tempArray.length-1;i++)
{
if(tempArray[i].length == tempArray[i+1].length)
{
tempArray = doubMatrix;
}
}
}
else
{
makeDoubMatrix(1,1);
}
}
public int getDim1()
{
return doubMatrix.length;
}
public int getDim2()
{
return doubMatrix[0].length;
}
private void makeDoubMatrix(int row, int col)
{
double[][] tempArray = new double[row][col];
for (int i = 0;i < row;i++)
{
for(int j = 0;j < col;j++)
{
tempArray[i][j] = Math.random() * (100);
doubMatrix[i][j] = tempArray[i][j];
}
}
}
public DoubleMatrix addMatrix(DoubleMatrix secondMatrix)
{
//this. doubMatrix = doubMatrix;
double[][] tempArray;
if(secondMatrix.doubMatrix.length == doubMatrix.length)
if(secondMatrix.doubMatrix[0].length == doubMatrix[0].length)
{
tempArray = new double[doubMatrix.length][doubMatrix[0].length];
for(int i = 0; i< secondMatrix.doubMatrix.length;i++)
for(int j = 0; j< secondMatrix.doubMatrix[i].length;j++ )
{
tempArray[i][j] = secondMatrix.doubMatrix[i][j] + doubMatrix[i][j];// add two matrices
}//end for
return new DoubleMatrix (tempArray);
}
return new DoubleMatrix(1,1);
}
public DoubleMatrix getTransposedMatrix()
{
double[][] tempArray = new double[doubMatrix.length][doubMatrix[0].length];
for(int i = 0;i < doubMatrix.length;i++)
for(int j = 0;j < doubMatrix[i].length;j++)
{
tempArray[j][i] = doubMatrix[i][j];// transposed matrix2
}//end for
return new DoubleMatrix(tempArray);
}
public DoubleMatrix multiplyingMatrix(DoubleMatrix secondMatrix)
{
double[][] tempArray = new double[secondMatrix.doubMatrix.length][doubMatrix[0].length];
//check if dimension of matrix1 equal to dimension of matrix2
if(secondMatrix.doubMatrix[0].length == doubMatrix.length)
if(doubMatrix.length == secondMatrix.doubMatrix[0].length)
{
for (int i = 0; i <secondMatrix.doubMatrix.length; i++)
{
for(int j = 0; j < doubMatrix[0].length; j++)
{
for (int k = 0; k < doubMatrix.length; k++)
{
tempArray[i][j] = tempArray[i][j] + secondMatrix.doubMatrix[i][k]*doubMatrix[k][j]; // multiply 2 matrices
}
}
}//end for
}// end if
return new DoubleMatrix(1,1);
}
public void printMatrix(String text)
{
System.out.println(text);// output string
for(int i = 0; i< doubMatrix.length;i++)
{
for(int j = 0; j< doubMatrix[i].length;j++ ) {
System.out.printf("%9.1f", doubMatrix[i][j]);// out put value for matrices
}
System.out.println();
}
}
}
public class Program3
{
public static void main(String[] args)
{
int num1 = (int) (Math.random()*(10-3+1)+3);
int num2 = (int) (Math.random()*(10-3+1)+3);
DoubleMatrix doubMatObj1 = new DoubleMatrix(num1,num2);
DoubleMatrix doubMatObj2 = new DoubleMatrix(doubMatObj1.getDim1(),doubMatObj1.getDim2());
DoubleMatrix doubMatObj3;
doubMatObj2.getDim1();
doubMatObj3 = doubMatObj1.addMatrix(doubMatObj2);
doubMatObj1.printMatrix("First Matrix Object");
doubMatObj2.printMatrix("Second Matrix Object");
doubMatObj3.printMatrix("Result of Adding Matrix Objects");
doubMatObj2 = doubMatObj2.getTransposedMatrix();
doubMatObj2.printMatrix("Result of inverting Matrix Object");
doubMatObj3 = doubMatObj1.multiplyingMatrix(doubMatObj2);
doubMatObj3.printMatrix("Result of Multiplying Matrix Objects");
}
}
Hi, I have a NullPointerException error in the last line statement of the makeDoubMatrix method as well the call makedoubMatrix in side if statement of the first constructor.
doubMatrix seems to be null when I already initialize it. How will I be able to fix this problem ?
You want to initialize the array, i.e.:
private double[][] doubMatrix = new double[size1][size2];
where size1 and size2 are arbitrary sizes. What you probably want is:
if(row > 0 && col > 0)
{
doubMatrix = new double[row][col];
makeDoubMatrix(row,col);
}
else
{
doubMatrix = new double[1][1];
makeDoubMatrix(1,1);
}
which initializes the array doubMatrix to a size of row*col if both row and col are greather than 0, and to 1*1 otherwise, then calls makeDoubMatrix with its initialized size (you could have this method call after the if-else, using doubMatrix.size and doubMatrix[0].size, but I think it's more readable now).
Change the second constructor (which takes a 2D array) using the same reasoning.
You're not initializing doubMatrix. The only line which assigns a value to doubMatrix is this commented out one:
//this. doubMatrix = doubMatrix;
(And that wouldn't help.)
Ask yourself where you think you're initializing it - where do you think you've got something like:
doubMatrix = new double[1][2];
... or an assignment copying a value from another array:
doubMatrix = someOtherVariable;
If you haven't got any statements assigning it a value, you aren't initializing it, so it will always have the default value of null.

Categories

Resources