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.