Jump to content

2d masīvs izvada kolonu summu,nestrādā ja rindu un kolonu skaits nav vienāds


Recommended Posts

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 post
Share on other sites

 

 

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 post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...