How does the cycle count in String?



  • Hello, everyone. I have a question. I want the char filled with Random but so much as the user wants. The problem was that only one value was always returning, since every time in the cycle, the value was rewritten and the latter was retained.

    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;
    

    }



  • There's no compilator at hand, but there's got to be something like:

    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; // А здесь и так всё понятно (возвращаем не последний сгенерированный символ, а всю строку)
    

    }




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2