Taking the size of an Array at runtime & generate random numbers to populate the Array
By: Ganesh Iyer
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
}
}
Archived Comments
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Java program to get location meta data from an image
Program using concept of byte long short and int in java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Count number of vowels, consonants and digits in a String in Java
Student marks calculation program in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program