编辑并添加Java数组的总和

huangapple go评论69阅读模式
英文:

Editing and adding the sum of java arrys

问题

我正在尝试迭代一个数组并添加数组的总和,但不包括数字13及其后面的数字。示例[1,1,1,1,13,2] = [1,1,1,1,0,0] = 4

到目前为止,我所拥有的主要信息是如何检查数组中是否包含数字13以及如何将其更改为0。

public static int sum13(int[] nums) {
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] == 13) {
            nums[i] = 0;
            if (i + 1 < nums.length) {
                nums[i + 1] = 0;
            }
        }
    }

    int sum = 0;
    for (int num : nums) {
        sum += num;
    }

    return sum;
}

public static void main(String[] args) {
    int[] a = {1, 2, 3, 13, 4};
    int result = sum13(a);
    System.out.println(result);
}

这段代码将数组中的数字13及其后面的数字都替换为0,然后计算数组的总和并返回。

英文:

I am trying to iterate over an array and add the sum of the array except the number 13 and the number after it.
Example
[1,1,1,1,13,2] = [1,1,1,1,0,0] = 4

this is what I have so far the main things I need to know is how do I check if the array has a number 13 in it and how do I change it to a 0

   public static int sum13(int[] nums) {
       
       for(int i=0; i &lt; nums.length; i++) {
           
           if(nums.indexOf(i) == 13) {
               
           }
            
       }
        
    }
  


    
    
    public static void main(String[] args) {
        //this is the main method
        int[] a = {1,2,3,13,4};
        
        sum13(a);
        

}
}

答案1

得分: 2

public static int sum13(int[] nums) {
int sum = 0;
for (int i = 0; i < nums.length; i++) {

    if (nums[i] == 13) {
        break;
    }
    sum += nums[i];
}
return sum;

}
public static void main(String[] args) {
//this is the main method
int[] a = {1, 2, 3, 13, 4};

System.out.println(sum13(a));

}

英文:

You can try this , to skip adding all number when you get 13 in your array :

public static int sum13(int[] nums) {
	       int sum = 0;
	       for(int i=0; i &lt; nums.length; i++) {
	           
	           if(nums[i] == 13) {
	               break;
	           }
	            sum += nums[i];
	       }
	        return sum;
	    }
	  public static void main(String[] args) {
	        //this is the main method
	        int[] a = {1,2,3,13,4};
	        
	        System.out.println(sum13(a));
	        

	}

答案2

得分: 0

尝试这个。

public static int sum13(int[] nums) {
    return IntStream.of(nums).takeWhile(i -> i != 13).sum();
}
英文:

Try this.

public static int sum13(int[] nums) {
    return IntStream.of(nums).takeWhile(i -&gt; i != 13).sum();
}

huangapple
  • 本文由 发表于 2020年8月7日 11:44:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63294871.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定