0

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:

  • Type mismatch: cannot convert from int to char
  • The method next(int) from the type Random is not visible

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

1

2 Answers 2

3

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)];
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Your solution is correct, but your assumptions on why OP's code is wrong are not :) See my answer for clarification.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.