Reputation: 1
I need to take a random element from an array of char
s
Random casuale = new Random()
char[] arraySuits = {'c', 'c', 'c', 'q', 'q', 'q', 'f', 'f', 'f', 'p', 'p', 'p',};
location1S=casuale.next(arraySuits.length);
location2S=casuale.next(arraySuits.length);
There are two errors:
int
to char
next(int)
from the type Random
is not visibleThe errors are both at casuale.next(arraySuits.length)
but I don't know how to fix it.
Upvotes: 0
Views: 111
Reputation: 27119
Ok, there's a lot of confusion going on here
location1S=casuale.next(arraySuits.length);
there's no arraySuits
in view here, so we'll just assume you meant to call the array arraySuits
when you declared itcasuale.next(arraySuits.length)
returns a arraySuits.length
-bit random number, not a number between 0 and arraySuits.length
. And it is a protected
method anyway, so you can't use it unless your class inherits from Random
(hence the second error message). You need to use casuale.nextInt(arraySuits.length)
instead.location1S
which, according to your first error message and what your problem description implies (but your code does not actually show) is a char
. Instead you should assign it an element of arraySuits
with a random index, so arraySuits[casuale.next(arraySuits.length)]
All of this boils down to
Random casuale = new Random();
char[] arraySuits = {'c', 'c', 'c', 'q', 'q', 'q', 'f', 'f', 'f', 'p', 'p', 'p'};
location1S = arraySuits[casuale.next(arraySuits.length)];
location2S = arraySuits[casuale.next(arraySuits.length)];
Upvotes: 3
Reputation: 51
There are two issues here. The first is that location1s
and location2s
are not defined as a type. They need to be given a variable type. In this case that would be char
.
The second issue is that the .next
method does not exist in java.random for char
. You need to use the .nextInt()
method that will pull a random value from the arrayList. See below for example.
Random casuale = new Random();
char[] arraySuits = {'c', 'c', 'c', 'q', 'q', 'q', 'f', 'f', 'f', 'p', 'p', 'p',};
char location = arraySuits[casuale.nextInt(arraySuits.length)];
System.out.println(location); // prints out whatever random char was chosen.
Upvotes: 0