Java 如何找到数组中的奇数和偶数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19352569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 16:23:18  来源:igfitidea点击:

How to find the Odd and Even numbers in an Array?

javaarraysmethods

提问by Jeriel Ng

Right now, I'm trying to find the odd and even numbers of an array. Here's the code of what I have so far. I know my findEvens() and findOdds() methods are messed up because they keep giving me off values whenever I try to print the final result. For example, if I try to find the odds of {1,5,8,3,10}, it gives me {5,3,0}. And if I try to find the evens of {2,5,8,7,19}, it gives me {2,8,0}. Anyone know why?

现在,我正在尝试查找数组的奇数和偶数。这是我到目前为止所拥有的代码。我知道我的 findEvens() 和 findOdds() 方法搞砸了,因为每当我尝试打印最终结果时,它们都会给我提供值。例如,如果我试图找出 {1,5,8,3,10} 的几率,它会给出 {5,3,0}。如果我试图找到 {2,5,8,7,19} 的偶数,它会给我 {2,8,0}。有谁知道为什么?

public class Scores {
   private int[] numbers;
   public Scores(int[] numbersIn) {
      numbers = numbersIn;
   }
   public int[] findEvens() {
      int numberEvens = 0;
      for (int i = 0; i < numbers.length; i++) {
         if (i % 2 == 0) {
            numberEvens++;
         }
      }
  int[] evens = new int[numberEvens];
  int count = 0;
  for (int i = 0; i < numbers.length; i++) {
     if (numbers[i] % 2 == 0) {
        evens[count] = numbers[i];
        count++;
     }      
  }      
  return evens;
}
public int[] findOdds() {
  int numberOdds = 0;
  for (int i = 0; i < numbers.length; i++) {
     if (i % 2 == 0) {
        numberOdds++;
     }
  }
  int[] odds = new int[numberOdds];
  int count = 0;
  for (int i = 1; i < numbers.length; i++) {
     if (numbers[i] % 2 == 1) {
        odds[count] = numbers[i];
        count++;
     }      
  }      
  return odds;
 }
 public double calculateAverage() {
      int sum = 0;
      for (int i = 0; i < numbers.length; i++) {
         sum += numbers[i];
      }   
      return (double) sum / numbers.length;
   }
 public String toString() {
    String result = "";
    for (int i = 0; i < numbers.length; i++) {
       result += numbers[i] + "\t";
    }
    return result;
 }
public String toStringInReverse() {
  String result = "";
  for (int i = numbers.length - 1; i >= 0; i--) {
     result += numbers[i] + "\t";
  }
  return result;
  }
}                  

采纳答案by drees

You're problem is in counting how many even numbers you have

你的问题是计算你有多少偶数

public int[] findEvens() {
  int numberEvens = 0;
  for (int i = 0; i < numbers.length; i++) {
     if (i % 2 == 0) {
        numberEvens++;
     }
  }

this will always return a number that is half the size of the length of numbers because you're doing mod division on the number of elements in the array, not on the elements themselves. Add numbers[i]to the ifstatement

这将始终返回一个数字长度的一半大小的数字,因为您正在对数组中的元素数量进行 mod 除法,而不是对元素本身进行除法。添加numbers[i]if声明中

public int[] findEvens() {
  int numberEvens = 0;
  for (int i = 0; i < numbers.length; i++) {
     if (numbers[i] % 2 == 0) {
        numberEvens++;
     }
  }

looks like you've got the same problem with odd count

看起来你对奇数有同样的问题

回答by Omar Faroque Anik

'i' is used as conditional variable for looping. You should not divide this by 2. You have to divide the array element. like

'i' 用作循环的条件变量。您不应将其除以 2。您必须将数组元素除以。喜欢

      if (numbers[i] % 2 == 0) {
        numberEvens++;
     }

then it should work. Thanks

那么它应该工作。谢谢

回答by Gaurav Sachdeva

Try This Code

试试这个代码

import java.util.Scanner;
public class OddEven {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("enter number Elements in Array");
        int n = s.nextInt();
        int arr[] = new int[n];
        System.out.println("enter Elements ");
        for(int i=0; i<n; i++) {
            arr[i]=s.nextInt();
        }
        int [] odd = filterOdd(arr);
        try {
            for(int i=0; i<n; i++) {
                System.out.println("Odd" + odd[i]);
            }
        } catch(ArrayIndexOutOfBoundsException e) {}
        int [] even = filterEven(arr);
        try {
            for(int i=0; i<n; i++) {
                System.out.println("Even" + even[i]);
            }
        } catch(ArrayIndexOutOfBoundsException e) {}
    }
    public static int[] filterOdd(int[] a) {
        int l = 0;
        int j = 0;
        for(int i=0; i<a.length; i++) {
            if(a[i]%2==1) {
                l++;
            }
        }
        int k[]=new int[l];
        for(int i=0; i<a.length; i++) {
            if(a[i]%2==1) {
                k[j] = a[i];
                j++;
            }
        }
        return k;
    }
    public static int[] filterEven(int[] a) {
        int l = 0;
        int j = 0;
        for(int i=0; i<a.length; i++) {
            if(a[i]%2==0) {
                l++;
            }
        }
        int k[] = new int[l];
        for(int i=0; i<a.length; i++) {
            if(a[i]%2==0) {
                k[j] = a[i];
                j++;
            }
        }
        return k;
    }
}

回答by Sabuj Karmaker

public class Array {


    public static void main(String[] args) {
        // TODO code application logic here
        //Array declaration and value asign
        int number[]=new int[]{1,2,3,4,5,6,7,8,9};
        // for loop to move number
        for(int p=0;p<number.length;p++)
        {
            // check number is even or odd??
            if(number[p]%2==0)

                System.out.println(number[p]+ " is Even number");
            else
                System.out.println( number[p]+" is odd umber");




        }

                }


}

回答by sunil waghole

Odd array one columns and another columns even array

奇数数组一列和另一列偶数数组

public class OddEven {

     public static void main(String[] args) {

        int arr[]={1,2,3,4,5,6,7,8};
        int ss[]=new int[10];
        int odd[]=new int[10];
        int i;
        int k;

        for( i=0;i<arr.length;i++)
        {
            if(arr[i]%2==0)
            {
               ss[i]=arr[i];
               System.out.print(""+ss[i]);
               System.out.print(" ");
            }

            if((arr[i]%2)!=0)
            {
                 odd[i]=arr[i];

                 System.out.print(""+odd[i]);
                 System.out.print(" ");
            }else
            {
                 System.out.println(" ");
            }
        }
    }
}

========================================output============================== 1 2
3 4
5 6
7 8

========================================输出========== ====================== 1 2
3 4
5 6
7 8