Reputation: 25
Hi I have a snippt of my Homework ...and I am getting a different value from what I should be expecting here are my class variables
I have : seed ....(through scanner should be : 12345 -testing value so I get get the same results as my instructor-) LenghtOfArray ....(through scanner too) Final MAX = 8;
I didn't know how to coordonate within my code to get it to work
and I have the for loop :
Random Obj = new Random (seed);
int []myArray = new int [LengthOfArray];
for(int i = 0 ; i < myRandomArray.length ; i++) {
myArray[i] = (int) Obj.nextLong();
System.out.print(myArray[i] + " ");
}
System.out.println();
Now I am missing MAX
variable so my output should be :
4 4 6 0 4 4 7 0 7 6 5 6
but I get this :
-70013384 64862043 543438317 1940859862 924168001 1943285380 -62817581 -1920529480 541298859 -1439409345 520340403 -1293274375
so how can I enforce my code to get the out come in the range of my MAX (which is < 8)
Upvotes: 1
Views: 53
Reputation: 1
Length of your array should be 12, not 8. Then to get a number between 0 and 8 to store in your array use
Obj.nextInt(9);
Upvotes: 0
Reputation: 201409
If I understand your question, first define MAX
-
final int MAX = 8;
And use Random.nextInt(int)
to specify the maximum value (exclusive, so 0 - MAX-1
) like
myArray[i] = Obj.nextInt(MAX);
Finally, you should really rename your Random
instance (Obj
is both a bad variable name and poorly capitalized per Java's naming conventions - variables start with a lower case letter). In Java 8+, you might also use IntStream
and lambdas to write it like
Random rand = new Random();
int lengthOfArray = 10;
final int MAX = 8;
int[] myArray = IntStream.generate(() -> rand.nextInt(MAX)) //
.limit(lengthOfArray).toArray();
System.out.println(IntStream.of(myArray).mapToObj(String::valueOf) //
.collect(Collectors.joining(" ")));
Upvotes: 2
Reputation: 31868
You probably are looking for nextInt(int n)
method from the Random
class which can be used as:
myArray[i] = obj.nextInt(9); //including 8 and 0
PS: obj
here is your Obj
, just that I prefer following camelCase convention.
Upvotes: 2