Error using Random in JAVA

Asked

Viewed 122 times

3

When I run this code:

public class main 
{
    static boolean terminar = false;

    public static void main(String[] args)
    {
        long init  = System.currentTimeMillis(); 

        BruteForce(true, true, "a123", 10, 10000);

        long end  = System.currentTimeMillis(); 
        long diff = end - init;
        System.out.println("Demorou " + (diff / 1000) + " segundos");
    }
    public static String BruteForce(boolean numeros, boolean letras, String busca,int maxCaracteres,  int limite)
    {
        ArrayList<String> old = new ArrayList<String>();
        ArrayList<String> caracteres = new ArrayList<String>();

        Random rand = new Random();

        String[] todos = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "a", "b", "c", "d", "e", "f", "g"
                          , "h", "i", "j", "k", "l", "m", "n", "o", "p", "k", "r", "s", "t", "u", "v", "w", "x", "y", "z"
                          , "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U"
                          , "V", "W", "X", "Y", "Z", "'", "!", "@", "#", "$", "£", "%", "¢", "¨", "¬", "&", "*", "(", ")", "_", "-"
                          , "+", "=", "§", "/", ".", "[", "]", "`", "´", "{", "}", "º", "^", "~", "<", ">", ":", ";", "?", "°", "ª",
                          "|", "¹", "²", "³"};

        for(int j = 0; j < todos.length; j++)
        {
            caracteres.add(todos[j]);
        }

        String combinacao = "";
        int quantCaracteres = 1;
        int stop = todos.length * quantCaracteres;

        while(old.size() != stop)
        {   
            for(int i = 0; i < quantCaracteres; i++)
            {
                int randomico = rand.nextInt(todos.length + 1);

                combinacao = "" + combinacao + todos[randomico];
            }

            if(combinacao.equals(busca))
            {
                return combinacao;
            }

            if(!old.contains(combinacao))
            {
                old.add(combinacao);
                System.out.println("Size:" + old.size() + " Stop:" + (stop -1) + " Todos:" + todos.length);
                System.out.println(combinacao);
            }

            combinacao = "";

            if(old.size() == stop)
            {
                quantCaracteres++;
            }
        }

        return "Nada";
    }
}

He makes that mistake

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 107
at me.lordlokon.main.BruteForce(main.java:49)
at me.lordlokon.main.main(main.java:14)

The line 49 is this:

combinacao = "" + combinacao + todos[randomico];

1 answer

6


Look at this:

        int randomico = rand.nextInt(todos.length + 1);

        combinacao = "" + combinacao + todos[randomico];

According to the javadocs of the method nextInt(int):

Returns a pseudorandom, uniformly Distributed int value between 0 (inclusive) and the specified value (exclusive)

What translating into Portuguese is:

Returns a pseudorandom, evenly distributed int value between 0 (inclusive) and the specified value (exclusive)

That is, it will be between 0 and todos.length.

Aconntece that the last array position todos is the position todos.length - 1. When the generated number is todos.length, will give a ArrayIndexOutOfBoundsException.

What you wanted was this:

        int randomico = rand.nextInt(todos.length);

        combinacao = "" + combinacao + todos[randomico];

I mean, just take the + 1 of the code.

And finally, a hint that has nothing to do with random numbers: Follow the language naming conventions. The class name main should start with uppercase letter and method name BruteForce should start with lower case letter.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.