简体   繁体   English

java - 如何将二维数组中一行中的所有数字相加

[英]how to add all numbers from a row in a two dimensional array java

I am writing Java in Eclipse IDE, I have this 2D array:我正在 Eclipse IDE 中编写 Java,我有这个二维数组:

public static void main(String[] args) {
int[][] fravaer18S = {
{ 2, 0, 0, 0, 3, 1, 0, 2, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 2, 0, 0, 0, 3, 1, 0, 2, 0, 0, 0, 0 },
{ 1, 2, 1, 2, 1, 2, 0, 2, 0, 0, 4, 0 },
{ 5, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0 }};

In another Class, I am supposed to write code so that a person can give a column number, and all numbers from that column is then added together.在另一个班级中,我应该编写代码以便一个人可以给出一个列号,然后将该列中的所有数字相加。

So f.ex.所以f.ex。 a person gives row 3, and the code returns 15.一个人给出第 3 行,代码返回 15。

This stump of code was given:给出了这段代码:

 public int samletFravaer(int[][] fravaer, int elevNr) {
    // TODO
    return -1;

How do I code that?我该如何编码? And what do I need to write in my main?我需要在我的主要内容中写什么?

Add boundry conditions or exception handling on your own.自行添加边界条件或异常处理。

public int samletFravaer(int[][] fravaer, int elevNr) {
    int sum = 0;
    for (int i = 0; i < fravaer[elevNr].length; i++) {
      sum += fravaer[elevNr][i];
    }
    return sum;
  }

Could also be done using foreach loop也可以使用 foreach 循环来完成

public static int samletFravaer(int[][] fravaer, int elevNr){
    int ri = 0;
    for(int i: fravaer[elevNr]){
        ri += i;
    }
    return ri;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM