[英]Method to add the even/odd numbers
I have an array with several numbers:我有一个包含多个数字的数组:
int[] tab = {1,2,3,4};
I have to create two methods the first is the sum() method and the second is numberOdd() .我必须创建两个方法,第一个是sum()方法,第二个是numberOdd() 。
It's Ok for this step !这一步没问题!
int length = tab.length;
length = numberOdd(tab,length);
int sum_odd = sum(tab, length);
System.out.println(" 1) - Calculate the sum of the odds numbers : => " + sum_odd);
public static int sum(int[] tab, int length){
int total = 0;
for(int i=0;i<length;i++){
total += tab[i];
}
return total;
}
public static int numberOdd(int[] tab, int length){
int n = 0;
for(int i=0;i<length;i++){
if(tab[i] % 2 != 0){
tab[n++] = tab[i];
}
}
return n;
}
Now, I have to add the even numbers with the numberEven() method and I get the value "0".现在,我必须使用numberEven()方法添加偶数,然后得到值“0”。
I don't understand why I retrieve the value => 0 ???????我不明白为什么我要检索值 => 0 ???????
Here is my code:这是我的代码:
int[] tab = {1,2,3,4};
int length = tab.length;
length = numberOdd(tab,length);
int sum_odd = sum(tab, length);
length = numberEven(tab,length);
int sum_even = sum(tab, length);
System.out.println(" 1) - Calculate the sum of the odds numbers : => " + sum_odd);
System.out.println(" 2) - Calculate the sum of the evens numbers : => " + sum_even);
}
public static int numberEven(int[] tab, int length){
int n = 0;
for(int i=0;i<length;i++){
if(tab[i] % 2 == 0){
tab[n++] = tab[i];
}
}
return n;
}
For information: I share the code here => https://repl.it/repls/CriminalAdolescentKilobyte有关信息:我在这里分享代码 => https://repl.it/repls/CriminalAdolescentKilobyte
Thank you for your help.感谢您的帮助。
you have changed the array in your numberOdd() method.您已更改 numberOdd() 方法中的数组。 try replacing
tab[n++] = tab[i];
尝试更换
tab[n++] = tab[i];
with n++;
与
n++;
public static int sumEven(int[] tab){
int sumEven = 0;
for(int i=0;i<tab.length;i++){
if(tab[i] % 2 == 0){
sumEven = sumEven + tab[i];
}
}
return sumEven;
}
This should work.这应该有效。
tab[i]
to n
tab[i]
添加到n
length
as a parameter to numberEven
does not cause any harm but you don't need it.length
作为numberEven
的参数不会造成任何伤害,但您不需要它。 Given below is the working example:下面给出的是工作示例:
public class Main {
public static void main(String[] args) {
int[] tab = { 1, 2, 3, 4 };
System.out.println(numberEven(tab));
}
public static int numberEven(int[] tab) {
int n = 0;
for (int i = 0; i < tab.length; i++) {
if (tab[i] % 2 == 0) {
n += tab[i];
}
}
return n;
}
}
Output:输出:
6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.