SoManyQuestions SoManyQuestions - 1 year ago 48
Java Question

customize the number of digits when shown the alphabet

The code for displaying all combinations 5 letters is:

for(char alphabet = 'A'; alphabet <= 'Z';alphabet++)
for(char s = 'A'; s <= 'Z';s++)
for(char b = 'A' ; b <= 'Z';b++)
for(char f = 'A'; f <= 'Z'; f++)
for (char d = 'A'; d <= 'Z'; d++)
System.out.println(alphabet+""+s+""+b+""+f+ ""+d );

But my boss wants a version in which you could customize which number of letters is displayed for example if he enters "3" it should display "aaa" and if he enters 5 it should display "aaaaa" and that for all combinations of a to z.

Answer Source


public static class Main {

    public static void main() {

    static void printAll(String prefix, int n) {
        if( n==0 ) {
        } else {
            for(char c='A'; c<= 'Z'; c++) {
                printAll(prefix+c, n-1);

Beware! Only run with small values of n!