Source of ArrayReturn.java


  2: import java.util.Scanner;
  3: import java.util.Arrays;

  5: /**
  6:  * A program demonstrating methods that return arrays.
  7:  *
  8:  * @author Mark Young (A00000000)
  9:  */
 10: public class ArrayReturn {

 12:     public static void main(String[] args) {
 13:         // create the variables
 14:         Scanner kbd = new Scanner(System.in);
 15:         int numDice;
 16:         int[] rolled;

 18:         // read the number of dice
 19:         System.out.print("How many dice should I roll? ");
 20:         numDice = kbd.nextInt();
 21:         kbd.nextLine();

 23:         // create the array object
 24:         rolled = dice(numDice);

 26:         // print the result
 27:         System.out.println("\n"
 28:                 + "The dice I rolled were: "
 29:                 + Arrays.toString(rolled));
 30:     }

 32:     /**
 33:      * A method to roll a certain number of dice and return the results.
 34:      *
 35:      * @param howMany   how many dice are to be rolled
 36:      * @return          an array containing the results of howMany die rolls
 37:      */
 38:     public static int[] dice(int howMany) {
 39:         // create the array object, just big enuf to hold all the rolls
 40:         int[] result = new int[howMany];

 42:         // roll the dice, saving the results in the array
 43:         for (int i = 0; i < howMany; ++i) {
 44:             result[i] = 1 + (int)(Math.random() * 6);
 45:         }

 47:         // return the array
 48:         return result;
 49:     }

 51: }