2

I am learning java, and my assignment now is to simulate a chess notation.

I have done random int codes, but not sure how to make a random letter code, and the thing is I only need to choose random letters from A to H, I have seen random all 26 letter generators but could not work my way to understand how to generate only A to H.

My other concern is will I be able to store char and ints in a matrix [k][8] or do I have to initialise it in a special way?

The idea is to create the class and later try and randomly generate chess notation. At this stage, the notations do not have to make sense.

Here is what I used for int random

import java.util.Random;

static Random rnd = new Random();
static int rnd(int A, int B) { 
    return A + rnd.nextInt(B - A + 1);

Also, how can I make the random selection from specified letters that will represent the chess figures?

I don't need exact codes a push to the right direction will be more than enough.

catch23
  • 17,519
  • 42
  • 144
  • 217
Ryne Ignelzy
  • 137
  • 1
  • 2
  • 13
  • You can add the letters into an array and then use Math.random for the array index – AMB Mar 31 '17 at 12:11
  • 2
    `return 'A' + rnd.nextInt(8);` and don't forget to cast the result to a `char`. Also, this might identify a column on a chess board - but it doesn't represent a chess figure (or a chess square). – Elliott Frisch Mar 31 '17 at 12:11
  • Thanks, yeah for chess figures I have in mind creating another random function that would pick from the given chess figures available. Not sure if that is the best way, but that is what I have in my head – Ryne Ignelzy Mar 31 '17 at 12:20

2 Answers2

4

What about something like this?

Random rnd = new Random();
String characters = "ABCDEFGH";
char randomChar = characters.charAt(rnd.nextInt(characters.length()));
Alex Romanov
  • 11,453
  • 6
  • 48
  • 51
1

You can create a utility class for this with static method:

public final class RandomUtils {
    private static Random random = new Random();

    public static char generateRandomChar() {
        char[] chars = "ABCDEFGH".toCharArray();
        return chars[random.nextInt(chars.length)];
    }
catch23
  • 17,519
  • 42
  • 144
  • 217