java - How to store random integers into an instance of a class -


i tasked create 10 instances of square class within loop using 10 random integer values (10 - 20) length , store 10 square instances in sqarray , print out length , area of elements in array.

here code square class

public class square {      private int length;         // create constructor takes in len parameter        public square(int len){             length = len;        }         public int getlength(){             return length;        }         public double calculatearea(){             return length * length;         } } //square 

here code main class

public class squareuser {      public static void main(string[] args) {          //create instance of array sqarray.         square[] sqarray = new square [10];          for(int = 0; < sqarray.length; i++) {              sqarray[i] = (int) (math.random()*10);         }     } } 

as can see, didn't in main class don't know question talking about. have 2 questions:

  1. how generate random integer in loop if data type object?

  2. what mean "store 10 square instances in sqarray"? asking me store random integers in sqarray?

you need generate random integer between 10 , 20 , set created object :

public class squareuser {          public static void main(string[] args) {              //create instance of array sqarray.             square[] sqarray = new square [10];              for(int = 0; < sqarray.length; i++) {                  int val = 10 + (int) (math.random()*10);                 sqarray[i] = new square(val);                 system.out.println("length "+val);                 system.out.println("area "+sqarray[i].calculatearea());             }         }     } 

Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -