How can random characters be generated with Math.random?

0

I am trying to generate license plates for random cars that autogenerate in the constructor of a car class. The license plates are composed of 4 digits and 3 letters. For example: 0001JFK, 2245HRY etc.

How can I randomly generate letters and fill in the number with the zeroes if it is not 4 digits?

This is the code I have:

for (int i = 0; i < 50; i++) {
            matricula=(int) (Math.random()*9999+1); 
            System.out.print(matricula+"  ");
        }
    
asked by David Palanco 26.04.2018 в 15:24
source

2 answers

3

To generate random values in Java there is a class called Random in the package java.util.Random . This class has methods that allow you to obtain pseudo-random numbers.

To solve your problem we will use the table of characters ASCII and the method nextInt() of class Random to generate integer values between 0 and 9 to obtain the digits, and also between 65 and 90 to obtain the letters from the conversion of whole numbers to characters of the table ASCII .

So that we can use the class Random we have to first import the java.util.Random package at the beginning of our source file. This is the way to import it:

import java.util.Random;

Then you can implement this part code to store your registration with random values as text string:

// Inicializamos la variable que almacenará la matrícula.
String Matricula = "";
// Inicializamos la instancia de la clase Random con la que
// generaremos el valor aleatorio.
Random rnd = new Random();

// Creamos un ciclo que se ejecute 7 veces, que corresponden al
// texto de la matrícula.
for (int i = 0; i < 7; i++)
{
    // Con este condicional verificamos si estamos en la parte
    // numérica o alfabética de la matrícula.
    // Solo debe entrar al condicional si estamos generando los
    // números de la matrícula.
    if(i < 4)
    {
        // Con esta instrucción se genera un número aleatorio entre
        // 0 y 9, no se incluye el 10.
        Matricula += rnd.nextInt(10);
    }
    // Entrará en esta parte del condicional cuando estemos generando
    // las letras de la matrícula.
    else
    {
        // Con esta instrucción se genera un número aleatorio entre
        // 65 y 90, no se incluye el 91. Luego se convierte a un 
        // caracter ASCII.
        Matricula += (char)(rndnextInt(91) + 65);
    }
}

// Por último imprimimos la matrícula en la consola.
System.out.println("La matrícula es: " + Matricula);
  

So that way you would have the code that I propose for your problem:

...
import java.util.Random;

public static void main(String[] args) 
{
    String Matricula = "";
    Random rnd = new Random();

    for (int i = 0; i < 7; i++)
    {
        if(i < 4)
        {
            Matricula += rnd.nextInt(10);
        }
        else
        {
            Matricula += (char)(rndnextInt(91) + 65);
        }
    }

    System.out.println("La matrícula es: " + Matricula);
}

If you wish that the alphabetical part of the randomly generated registration does not contain a series of characters you can use the indexOf() method of the class String in conjunction with a loop while to compare if the character generated is in the list of letters that you do not want to appear in your registration and thus not print it.

  

To achieve this, together with the Random.nextInt() method, I propose the following code:

...
import java.util.Random;

public static void main(String[] args) 
{
    char Caracter;
    String Matricula = "";
   // Aquí se definen las letras que no quieres que se generen.
    String CaracteresNoDeseados = "AEIOU";
    Random rnd = new Random();

    for (int i = 0; i < 7; i++)
    {
        if(i < 4)
        {
            Matricula += rnd.nextInt(10);
        }
        else
        {
                do 
            {
                Caracter = (char)(rndnextInt(91) + 65);
            // Si el carácter existe en la cadena de texto 
            // de los no deseados, se repite el bucle
            } while (CaracteresNoDeseados.indexOf(Character) >= 0)

            Matricula += Caracter;
        }
    }

    System.out.println("La matrícula es: " + Matricula);
}

In this guide that talks about how to generate random numbers with class Random . You will also find that you can generate a random number with the class Math and its method random in this page . Using the Math.random method is also valid, so you could also try applying it for your solution.

  

If you want to change the use of the Random.nextInt() method by the method    Math.random() you must delete the line where you declare the   variable rnd and change the following lines of code:

Matricula += rnd.nextInt(10);
     

By:

Matricula += (int) Math.floor(Math.round() * 10);
     

Y

Matricula += (char)(rndnextInt(91) + 65);
     

By:

Matrícula += (char)((int) Math.floor(Math.round() * 91 + 65));

For more information about creating random values, see the following answer :

  

In Java there are two main classes for generating numbers   Random:

     

java.util.Random

     

java.security.SecureRandom

     

The Math.random () function uses java.util.Random just in case.

    
answered by 27.04.2018 / 03:18
source
0

I have managed to do it this way:

    private String generarMatricula() {
    matricula = "";
    int a;
    for (int i = 0; i < 7; i++) {
        if (i < 4) {    // 0,1,2,3 posiciones de numeros
            matricula = (int) (Math.random() * 9) + "" + matricula;

        } else {       // 4,5,6 posiciones de letras
            do {
                a = (int) (Math.random() * 26 + 65);///
            } while (a == 65 || a == 69 || a == 73 || a == 79 || a == 85);

            char letra = (char) a;
            if (i == 4) {
                matricula = matricula + "-" + letra;
            } else {
                matricula = matricula + "" + letra;
            }

        }
    }
    return matricula;
}

But I'm going to try indexOf to remove the vowels.

    private String generarMatricula() {
    matricula = "";
    int a;
     String CaracteresNoDeseados = "AEIOU";
    for (int i = 0; i < 7; i++) {
        if (i < 4) {    // 0,1,2,3 posiciones de numeros
            matricula = (int) (Math.random() * 9) + "" + matricula;

        } else {       // 4,5,6 posiciones de letras
            do {
                a = (int) (Math.random() * 26 + 65);///
            } while (CaracteresNoDeseados.indexOf(a) >= 0);

            char letra = (char) a;
            if (i == 4) {
                matricula = matricula + "-" + letra;
            } else {
                matricula = matricula + "" + letra;
            }

        }
    }
    return matricula;

Both forms work well

    
answered by 28.04.2018 в 16:58