How to create a one-dimensional array of strings filled with random characters. Each line has a length of 5.
Closed due to the fact that the issue is too general for the participants Wiktor Stribiżew , Denis Bubnov , rjhdby , ermak0ff , Vadizar 4 Mar '17 at 10:54 .
Please correct the question so that it describes the specific problem with sufficient detail to determine the appropriate answer. Do not ask a few questions at once. See “How to ask a good question?” For clarification. If the question can be reformulated according to the rules set out in the certificate , edit it .
2 answers
It generates random five-character strings from characters with codes 33 through 126. There is further DEL, so it would have to do other processing for large codes.
At each iteration, we generate a random number from 33 to 126, cast to char and create a character by code. So 5 times. Using StringBuilder, we collect a string.
public static void main(String[] args) { Scanner in = new Scanner(System.in); int STR_LENGTH = 5; System.out.println("Введите количество случайных строк"); int n = in .nextInt(); String[] arr = new String[n]; Random r = new Random(); for (int i = 0; i < n; i++) { StringBuilder builder = new StringBuilder(); for (int j = 0; j < STR_LENGTH; j++) { char code = (char) (r.nextInt(94) + 33); builder.append(Character.toString(code)); } arr[i] = builder.toString(); } System.out.println(Arrays.toString(arr)); } another option: you can use the Java Stream API
char[] chars = IntStream.rangeClosed('А', 'я') // указываем диапазок символов, тут весь русский алфавит .mapToObj(c -> "" + (char) c) .collect(Collectors.joining()).toCharArray(); // собираем в массив String res = new Random().ints(5, 0, chars.length) // рандомно выбираем 5 чисел от 0 до 64 .mapToObj(i -> String.valueOf(chars[i])). // берем значение из массива collect(Collectors.joining(", ")); // склеиваем через " ," System.out.println(res); result
У, й, а, Я, Р х, Л, е, в, Щ - The length of the
charsarray is not66, but64, so there’s not the whole alphabet - it’s worth fixing it in the comments to the code. You can also shorten the code usingint[] charCodes = IntStream.rangeClosed('А', 'я').toArray();, but this is an amateur. - Regent - thank. did not check the length - Senior Pomidor
- oneGood result turned out. - Nick Volynkin ♦
chars (akashort) usingMath.random, concatenate, ???, PROFIT !!! - Andrey M