Advertisement
Guest User

Untitled

a guest
Jun 28th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.50 KB | None | 0 0
  1. import java.util.*;
  2. /**
  3.  * EvenAndOdds: Generates 25 random numbers and sorts them.
  4.  * @author Cameron Roe
  5.  * @version 1.0 11/15/2010
  6.  */
  7. public class EvenAndOdds {
  8.     public static void main(String[] args) {
  9.         // We need arrays to hold the even and odd numbers.
  10.         int[] evens = new int[25];
  11.         int[] odds = new int[25];
  12.         // Seperate counters for each array. Makes it so we don't have numbers spread out in the arrays.
  13.         int evenCounter = 0, oddCounter = 0;
  14.         // Holds the random number
  15.         int num = 0;
  16.         // These are strings that will be printed after the array is formatted into a string
  17.         String oddStr, evenStr;
  18.         // Object of the Random class
  19.         Random rand = new Random();
  20.         for(int i = 0; i<25; i++) {
  21.             // Gets the random number.
  22.             num = rand.nextInt(100);
  23.             /**
  24.              * Checks if the number is even or odd
  25.              * Even: num % 2 == 0
  26.              * Odd: num % 2 != 0
  27.              */
  28.             if((num % 2) == 0) {
  29.                 evens[evenCounter] = num;
  30.                 evenCounter++;
  31.             } else {
  32.                 odds[oddCounter] = num;
  33.                 oddCounter++;
  34.             }
  35.         }
  36.         // Use the toString() method to format the array into a string.
  37.         evenStr = toString(evens);
  38.         oddStr = toString(odds);
  39.         // Print out the evens
  40.         System.out.println("Evens:");
  41.         System.out.println(evenStr);
  42.         // Print out the odds
  43.         System.out.println("Odds:");
  44.         System.out.println(oddStr);
  45.     }
  46.    
  47.     public static String toString(int[] e) {
  48.         String toStr = "";
  49.         for(int i = 0; i<e.length; i++) {
  50.             if(!(e[i] == 0)) {
  51.                 toStr += e[i] + " ";
  52.             }
  53.         }
  54.         return toStr;
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement