Programming Tutorials

Taking the size of an Array at runtime & generate random numbers to populate the Array

By: Ganesh Iyer in Java Tutorials on 2009-05-29  

A program which demonstrates by taking a number input from the screen and assign the length of the array at runtime alongwith output of an array elements randomly assigned within the input number.
//Author     : Ganesh Iyer, Mobile (0)9176148207
//Program    : Taking the size of an Array at runtime & generate random numbers to populate the Array
//Written on : 29th May 2009


//Include java packages

import java.io.*;
import java.lang.*;
import java.util.*;

class generateRan
{

   public static void main(String[] args)

   {

         int buffer, cnt;

   try {   // To catch error


       //One of the method provided by JAVA in taking input from the screen


        BufferedReader r = new BufferedReader(new InputStreamReader(System.in));

        System.out.println(\"Input the Array length in [0-9]\");


      //Casting string to Integer

        buffer = Integer.parseInt(r.readLine());


      //Check for zero & negative input through screen

           if (buffer==0 || buffer<0)
             {
                System.out.println(\"Not allowed\");
                System.exit(1);
             }

      //Here is the heart of the program where Array is taking its length

       int[] mx = new int[buffer];

       System.out.println(\"Populating Random elements for the array length are below \"+buffer);

           for (cnt=0; cnt< mx.length; cnt++)

           {

             mx[cnt] = (int) (Math.random()*buffer) + 1;

             System.out.print(\" \"+mx[cnt]);

           }

   } catch (IOException e) { //Output error
            System.err.println(\"Error occured\"+e);

    } // Closing exception

   }
}





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)