2014-02-10 46 views
-7
//check the error 
import java.util.Scanner; 
    class Matoe 
     { 
     public static void main(String args[]) 
    { 
     Scanner sc=new Scanner(System.in); 
     System.out.println("%n Enter rows and cols of the array:%n"); 
     int r=sc.nextInt(); 
     int c=sc.nextInt(); 
     int a[][]=new int[r][c]; 
     for(int i=1;i<=r;i++) 
     for(int j=1;j<=c;j++) 
     a[i][j]=sc.nextInt(); 
     for(int i=1;i<=r;i++) 
     for(int j=1;j<=c;j++) 
      { 
      if((i+j)%2!=0) 
      int sumeven+=a[i][j]; 
      else 
      int sumodd+=a[i][j]; 
      } 
     System.out.println("%n Sum of even element is:"+sumeven); 
    System.out.println("%n Sum of odd element is:"+sumodd); 
    } 
    } 
+1

什麼錯誤?我沒有看到任何。 – 2014-02-10 10:26:42

+3

請記住提問? – StuartLC

+2

我們不是編譯器。 – Raptor

回答

1

一個明顯的錯誤是數組是從零開始的,不基於1,即

for(int i=0;i<r;i++) 
    for(int j=0;j<c;j++) 
1

以下是錯誤:int sumeven+=a[i][j];

+=:平均取以前的變量值和另一個值吧

那麼是什麼你要做的就是你創建變量,但無initialze並使用+=


另一個錯誤:

你定義的局部變量中,如果statment並嘗試打印該值的範圍之外的if語句


int sumodd = 0; 
int sumeven = 0; 
Scanner sc = new Scanner(System.in); 
System.out.println("%n Enter rows and cols of the array:%n"); 
int r = sc.nextInt(); 
int c = sc.nextInt(); 
int a[][] = new int[r][c]; 
for (int i = 0; i < r; i++) { 
    for (int j = 0; j < c; j++) { 
     a[i][j] = sc.nextInt(); 
    } 
} 
for (int i = 0; i < r; i++) { 
    for (int j = 0; j < c; j++) { 
     if ((i + j) % 2 != 0) { 

      sumeven += a[i][j]; 
      System.out.println(a[i][j] + "odd"); 
     } else { 
      sumodd += a[i][j]; 
      System.out.println(a[i][j] + "even"); 
     } 
    } 
} 
System.out.println("%n Sum of even element is:" + sumeven); 
System.out.println("%n Sum of odd element is:" + sumodd);