Hello. I have this question. I want to make char fill with Random but with as many values ​​as the user wants. Faced the problem that always returns only one value, since each time going into a cycle, the value is rewritten and in fact the last is saved.

private static char codeGenerator(int needCharacters) { Random r = new Random(); String alphabet = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; for (int i = 0; i < needCharacters; i++) { generatedCode = alphabet.charAt(r.nextInt(alphabet.length())); } return generatedCode; } 

    2 answers 2

    There is no compiler at hand, but something like this should turn out:

     private static String codeGenerator(int needCharacters) { Random r = new Random(); String genstring; // Создаём результирующую строку для сгенерированных символов String alphabet = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; for (int i = 0; i < needCharacters; i++) { generatedCode = alphabet.charAt(r.nextInt(alphabet.length())); genstring = genstring + Character.toString(generatedCode); ; // А здесь просто добавляем к результирующей строке наш рандумный символ, заранее переведя в строку (toString) } return genstring; // А здесь и так всё понятно (возвращаем не последний сгенерированный символ, а всю строку) } 
    • In my case, your option was the best. Thank. - Maksims
    • @Maksims but not for that 😊 - alex-rudenkiy
    • @ alex-rudenkiy You can at least add StringBuilder to the code, but it’s not at all worth a lot of objects ...;) - Peter Slusar
    • @PeterSlusar well, in principle, you can use the "Bilder", but it will be a little harder for a beginner to understand :) - alex-rudenkiy

    You should declare an array of type char and write the returned values ​​to this array:

     private static char[] codeGenerator(int needCharacters) { Random r = new Random(); String alphabet = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; char result[] = new char[needCharacters]; for (int i = 0; i < needCharacters; i++) { result[i] = alphabet.charAt(r.nextInt(alphabet.length())); } return result; } 

    Note that the size of the array is actually the number of characters requested by the user.