artG Posted April 3, 2015 Share Posted April 3, 2015 Sveiki, jau iepriekšējā tēmā rakstīju,ka pašmācības ceļā mācos divdimensiju masīvus. Šoreiz ir problēma,ka programma strādā tikai tad ,ja rindu skaits ir vienāds ar kolonu skaitu, masīvs tiek izvadīts, bet nenotiek kolonu saskaitīsana, tā vietā izmet kļūdas paziņojumu " Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException" public class a { public static void main(String[] args) { int a[][] = new int [5][5]; int i,j; int s = 0; for(i= 0;i<a.length; i++) for(j = 0; j<a[i].length; j++){ a[i][j] = (int)(Math.random()*10); } for(i=0;i<a.length;i++){ for(j=0;j<a[i].length;j++) System.out.print(a[i][j] + "\t"); System.out.println(); } for (j = 0; j <a.length; j++){ for (i = 0; i <a[j].length; i++) s = s + a[i][j]; System.out.println("Kolonu elementu summa ir : " +s); s = 0; } } } Link to comment Share on other sites More sharing options...
nevertell Posted April 3, 2015 Share Posted April 3, 2015 Padomā, kas ir a.length. Link to comment Share on other sites More sharing options...
artG Posted April 3, 2015 Author Share Posted April 3, 2015 Padomā, kas ir a.length. labi, ja for (j = 0; j <a[j].length; j++){ for (i = 0; i <a.length; i++) s = s + a[i][j]; System.out.println("Kolonnas elementu summa ir : " +s); s = 0; Piemēram, ja i=2 un j=5; tad izvada tikai pirmo 2 kolonu summu, ne visu, kā to atrisināt? atrisināju pats, nomainot "for" ciklā "a[j].length" uz "a[0].length" jeb: for (j = 0; j <a[0].length; j++){ for (i = 0; i <a.length; i++) s = s + a[i][j]; System.out.println("Kolonnas elementu summa ir : " +s); s = 0; } Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now