简体   繁体   中英

Output all the odd and even numbers in the random numbers array

I declare an integer array of size 300, with random values from 1 to 500. I need to output all the even and odd numbers in the array 10 per line.

this is my code but I can't print 10 numbers per line and it doesn't print enough even and odd numbers in my array:

import java.util.Scanner;

public class Array {

   public static void main(String[] args)
   { 
      Scanner keyboard=new Scanner(System.in); 
   
      
      int[] A = new int[300]; 
      for(int i=0;i<A.length;i++)
      {
         A[i]=(int)(Math.random()*500+1);
      }
      
      for(int i=0;i<A.length;i++){
         System.out.print(A[i]+" ");
         if(((i+1) % 10) == 0){
            System.out.println();
         }         
      }
      System.out.println("Odd Numbers:"); 
       
      for(int i=0;i<A.length;i++){  
         if(A[i]%2!=0 && ((i+1) % 10) == 0){
            System.out.print(A[i]+" ");
         }
      }
      System.out.println();
      System.out.println("Even Numbers:"); 
      for(int i=0;i<A.length;i++){
      
         if(A[i]%2==0 && ((i+1) % 10) == 0){  
            System.out.print(A[i]+" ");  
         }  
      }
     
   
      
   }
}

You have to use a counter and check if it count % 10 == 0 . If yes, then move to the next line.

public static void main(String... args) {
    final IntPredicate odd = value -> value % 2 != 0;
    final IntPredicate even = value -> value % 2 == 0;

    int[] arr = randomArray(300);

    System.out.println("Odd Numbers:");
    printNumbers(arr, odd);

    System.out.println();
    System.out.println("Even Numbers:");
    printNumbers(arr, even);
}

private static int[] randomArray(int total) {
    Random random = new Random();

    return IntStream.range(0, total)
                    .map(i -> random.nextInt(500) + 1)
                    .toArray();
}

private static void printNumbers(int[] arr, IntPredicate predicate) {
    int i = 0;

    for (int value : arr) {
        if (predicate.test(value)) {
            System.out.format("%3d ", value);

            if (++i % 10 == 0)
                System.out.println();
        }
    }

    System.out.println();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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