检查该程序的错误

时间:2014-02-10 10:25:43

标签: java

//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);
    }
    }

2 个答案:

答案 0 :(得分:1)

一个明显的错误是数组基于零,而不是基于1,即

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

答案 1 :(得分:1)

以下是错误:int sumeven+=a[i][j];

+= :平均值取变量的先前值,添加另一个值

所以你要做的就是创建变量而不用初始化它并使用+=


另一个错误:

你在if语句中定义了局部变量,并尝试在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);