Asia Deiana
Asia Deiana

Reputation: 1

Random, Array and char in java

I need to take a random element from an array of chars

  1. C for hearts
  2. Q for diamonds
  3. F for clubs
  4. P for spades
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:

The errors are both at casuale.next(arraySuits.length) but I don't know how to fix it.

Upvotes: 0

Views: 111

Answers (2)

Federico klez Culloca
Federico klez Culloca

Reputation: 27119

Ok, there's a lot of confusion going on here

  1. 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 it
  2. casuale.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.
  3. You're trying to assign this random number to 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

Rich S
Rich S

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

Related Questions