Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- /**
- * EvenAndOdds: Generates 25 random numbers and sorts them.
- * @author Cameron Roe
- * @version 1.0 11/15/2010
- */
- public class EvenAndOdds {
- public static void main(String[] args) {
- // We need arrays to hold the even and odd numbers.
- int[] evens = new int[25];
- int[] odds = new int[25];
- // Seperate counters for each array. Makes it so we don't have numbers spread out in the arrays.
- int evenCounter = 0, oddCounter = 0;
- // Holds the random number
- int num = 0;
- // These are strings that will be printed after the array is formatted into a string
- String oddStr, evenStr;
- // Object of the Random class
- Random rand = new Random();
- for(int i = 0; i<25; i++) {
- // Gets the random number.
- num = rand.nextInt(100);
- /**
- * Checks if the number is even or odd
- * Even: num % 2 == 0
- * Odd: num % 2 != 0
- */
- if((num % 2) == 0) {
- evens[evenCounter] = num;
- evenCounter++;
- } else {
- odds[oddCounter] = num;
- oddCounter++;
- }
- }
- // Use the toString() method to format the array into a string.
- evenStr = toString(evens);
- oddStr = toString(odds);
- // Print out the evens
- System.out.println("Evens:");
- System.out.println(evenStr);
- // Print out the odds
- System.out.println("Odds:");
- System.out.println(oddStr);
- }
- public static String toString(int[] e) {
- String toStr = "";
- for(int i = 0; i<e.length; i++) {
- if(!(e[i] == 0)) {
- toStr += e[i] + " ";
- }
- }
- return toStr;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement