java - Print random numbers in array size 20 and print number in lndex number -


question:

write program create array of size 20 store integers. then, program should generate , insert random numbers between 1 , 7, inclusive array. next, program should print array output.
simple subset part of array consists of set of 4 elements next each other. program generate random number between 0 , 19, represents location in array (i.e. index number). then, program should print 4 elements location. program should take consideration boundaries of array. there no user input program.
program must include, @ least, following methods:
- insertnumbers, take input 1 integer array , store random numbers in it. - computelocation, generate location random number , return it.

a sample run of program shown below:

sample output #1:
array: 2 7 4 3 1 5 7 2 3 6 2 7 1 3 2 4 5 3 2 6
random position: 2
subset: 4 3 1 5

sample output #2:
array: 2 7 4 3 1 5 7 2 3 6 2 7 1 3 2 4 5 3 2 6
random position: 18
subset: 2 6 2 7

what have figured out far: public class assignmentquestion3 {

public static int insertnumbers(int n1,int n2) {     int min = n1;     int max = n2;             int randomnumber = min + (int) (math.random() * (max-min)+1);     return randomnumber; } public static int computelocation(int l1,int l2) {     int min = l1;     int max = l2;     int computelocation = min + (int) (math.random() * (max-min) + 1);     return computelocation; }  /**  * @param args command line arguments  */ public static void main(string[] args) {     // todo code application logic here int array[] ={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};  system.out.print("arrays: "); for(int = 0; < 20; i++) {     int random1 = insertnumbers(1, 7);     array[i] = random1;     system.out.print(array[i]+ " "); } 

your formula calculating random numbers between 1 , 7 (inclusive) wrong. computing random numbers between 2 , 7 (inclusive). missing parenthesis in formula.

so this:

int randomnumber = min + (int) (math.random() * (max - min) + 1); 

should this:

int randomnumber = min + (int) (math.random() * ((max - min) + 1)); 

because multiplication done before addition, version equals this:

int randomnumber = min + (int) ((math.random() * (max - min)) + 1); 

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

php - How do you embed a video into a custom theme on WordPress? -