java - How do I avoid getting NullPointerException in my Matrix sum? -


i want check if sum of each row in matrix equal. how should rewrite avoid npe?

i can make work "normal" matrices int[][] = {{1,2,3}, {4,5,6}}, want work when testing null , empty matrices.

public static boolean allrowsumsequal(int[][] m) {   boolean = false;   int x = 0;   int total = rowsum(m[0]);    (int = 0; < m.length; i++) {     (int j = 0; j < m[i].length; j++) {       x += m[i][j];     }     if (x != total) {       = false;       break;     } else {       x = 0;       = true;     }   }   return a; }  public static int rowsum(int[] v) {   int vsum = 0;   (int = 0; < v.length; i++) {     vsum += v[i];   }   return vsum; } 

you need define result or exception if want check "null" parameter. can return true if null valid or false otherwise.

if(m == null) return true; 

empty or 1 lined matrices can return true time , not require calculation:

if(m.length < 2) return true; 

the line test more simple, think:

// expect positiv result boolean result = true; // calculate first line int firstline = rowsum(m[0]);  // loop remaining lines (int = 1 ; < m.length ; i++){     // compare first line current line     if (firstline != rowsum(m[i]))     {        // not equal -> change result         result = false;        // break loop        break;     }    } return result; 

Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -