0

so I want to use Math.random instead of importing java.until.Random but keep the same output of my code

This is my code:

import java.util.Random;

public class MyStrings {

    public String randomAlphanumericString(int length) {

        String letters = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        String randomWord = "";
        Random random = new Random();
        for (int i = 1; i <= length; i++) {
            randomWord += String.valueOf(letters.charAt(random.nextInt(letters.length())));
        }
        return randomWord;
    }

    public boolean validAlphanumericString(String word) {

        for (char letter : word.toCharArray()) {
            if (Character.isLetter(letter) || Character.isDigit(letter)) {
            } else { System.out.println(word + " contains non alphanumeric characters");
                return false;
            }
        }
        return true;

    }


}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Wolf22
  • 21
  • 5

2 Answers2

0

I think you are looking for something like:

...    
    randomWord += String.valueOf(letters.charAt((int) (Math.random() * letters.length())));
...

From the JavaDoc for Math.random():

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

So that's why if you just multiply by the length and truncate it to int you get the range that you need.

leo277
  • 439
  • 2
  • 7
0

If you write a Lambda to get a random value, you can use it just like Random.nextInt()

IntFunction<Integer> rand = x-> (int)(Math.random()*x);

int v = rand.apply(10); // value between 0 and 9 inclusive.

WJS
  • 36,363
  • 4
  • 24
  • 39