英文:
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 < 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 < 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 -> i != 13).sum();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论