java - Brute Forcing - StackOverflowError -


i creating brute force program runs through possible strings, (for education purposes of course), , have problem... when :

package com.arinerron.tools.tools;  /**  *  * @author aaron  */ public class bruteforce {     public static char[] charset_alphabet = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n'};      private char[] charset = {'a', 'b', 'c', 'd'};     private int length = 3;      private int sofar = 1;      public bruteforce(char[] charset, int length) {         this.charset = charset;         this.length = length;     }      public string bruteforce() {         go("");         return "";     }      private void log(string t) {         system.out.println(t);     }      private void go(string w) {         for(int = 0; != this.charset.length; i++) {             string txt = w + this.charset[i];             if(sofar < length) {                 go(txt);             } else {              }             system.out.println(txt);         }         sofar++;     }      public static void main(string[] args) {         bruteforce bf = new bruteforce(bruteforce.charset_alphabet, 2);         bf.bruteforce();     } } 

i get:

exception in thread "main" java.lang.stackoverflowerror     @ java.lang.stringbuilder.append(stringbuilder.java:136)     @ com.arinerron.tools.tools.bruteforce.go(bruteforce.java:32)     @ com.arinerron.tools.tools.bruteforce.go(bruteforce.java:34)     @ com.arinerron.tools.tools.bruteforce.go(bruteforce.java:34)     @ com.arinerron.tools.tools.bruteforce.go(bruteforce.java:34)     @ com.arinerron.tools.tools.bruteforce.go(bruteforce.java:34)     @ com.arinerron.tools.tools.bruteforce.go(bruteforce.java:34)     @ com.arinerron.tools.tools.bruteforce.go(bruteforce.java:34)     @ com.arinerron.tools.tools.bruteforce.go(bruteforce.java:34)     @ com.arinerron.tools.tools.bruteforce.go(bruteforce.java:34)     @ com.arinerron.tools.tools.bruteforce.go(bruteforce.java:34)     @ com.arinerron.tools.tools.bruteforce.go(bruteforce.java:34)     @ com.arinerron.tools.tools.bruteforce.go(bruteforce.java:34)     @ com.arinerron.tools.tools.bruteforce.go(bruteforce.java:34)     @ com.arinerron.tools.tools.bruteforce.go(bruteforce.java:34) 

why? doesn't hard computer handle... :\

the issue increment sofar variable @ wrong place. condition starts new recursion true , causes stack overflow.

think of when sofar variable gets incremented. try moving sofar++; before recursive call go(txt) , see happens.

so:

private void go(string w) {     for(int = 0; != this.charset.length; i++) {         string txt = w + this.charset[i];         if(sofar < length) {             sofar++;             go(txt);                         }          system.out.println(txt);     }         } 

on side note: why returning empty string bruteforce() method? wouldn't void make more sense.


Comments