English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java Examples Comprehensive Guide
Neste exemplo, vamos aprender a gerar strings aleatórias e strings alfanuméricas aleatórias no Java.
import java.util.Random; class Main { public static void main(String[] args) { //Criar uma string que contém todos os A-A string do caractere Z String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //Criar um gerador de strings aleatórias StringBuilder sb = new StringBuilder(); //Criar um objeto da classe Random Random random = new Random(); //Specify the length of the random string int length = 7; for(int i = 0; i < length;++) { //Generate a random index number int index = random.nextInt(alphabet.length()); //Obter o caractere especificado pelo índice index //Da string char randomChar = alphabet.charAt(index); //Adicionar caracteres ao gerador de strings sb.append(randomChar); } String randomString = sb.toString(); System.out.println("Random string is: " + randomString); } }
Output Result
A string aleatória é: IIYOBRK
No exemplo acima, primeiro criamos uma string que contém todas as letras. Em seguida, usamos o método nextInt() da classe Random para gerar um índice aleatório.
Usando índices aleatórios, geramos caracteres aleatórios da string de letras. Em seguida, usamos a classe StringBuilder para concatenar todos os caracteres.
Se você quiser mudar a string aleatória para minúsculas, você pode usar o método toLowerCase() da String.
randomString.toLowerCase()
Atenção:Cada vez que você executar o programa, a saída será diferente.
import java.util.Random; class Main { public static void main(String[] args) { // Criar uma string composta por letras maiúsculas, minúsculas e números String upperAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String lowerAlphabet = "abcdefghijklmnopqrstuvwxyz"; String numbers = "0123456789"; //Juntar todas as strings String alphaNumeric = upperAlphabet + lowerAlphabet + numbers; //Criar um gerador de strings aleatórias StringBuilder sb = new StringBuilder(); //Criar um objeto da classe Random Random random = new Random(); //Specify the length of the random string int length = 10; for(int i = 0; i < length;++) { //Generate a random index number int index = random.nextInt(alphaNumeric.length()); // Get the character at index index from the string char randomChar = alphaNumeric.charAt(index); // Append the character to the string generator sb.append(randomChar); } String randomString = sb.toString(); System.out.println("Random string is: " + randomString); } }
Output Result
The randomly generated string is: pxg1Uzz9Ju
Here, we created a string that contains from0 to9ofnumbers and uppercase and lowercase letters.
From the string, we randomly generated a string of length10Alphanumeric string.