Search code examples
javacarrayspassword-generator

How can I return elements of my array in the given order?


My function is a password generator. It picks the amount of words in a sentence. And takes the firstLetter and the lastLetter alternately. Examples are in the void main method.

My problem is I don't know how to rotate the firstChar and lastChar. I tried it with modulo in a if statement but did not get me any further. Maybe you guys got some ideas.

public static String pwdgen(String s) {
    String[] Splitted = s.split(" ");
    int count = s.split(" ").length;
    int i = 0;
    String firstChar = "";
    String lastChar = "";

    for(i = 0; i < count; i = i + 1) {
        firstChar += Splitted[i].substring(0, 1);
        lastChar += Splitted[i].substring(Splitted[i].length() - 1);
    }


    return count + firstChar + lastChar;
}

public static void main(String[] args) {
    String pwd = pwdgen("Dies ist nur ein doofes Beispiel");
    System.out.println(pwd); // => "6Dtnndl"
    System.out.println(pwdgen("a b c")); // => 3abc
}

Solution

  • When you return the string in the password generator; you're returning all the first letters - then all the last letters:

    return count + firstChar + lastChar;
    

    In your for loop; instead of adding them into two seperate strings, add them into one the same string. You will need to keep a boolean to check whether you're adding the first or last letter though.

    public static String pwdgen(String s) {
        String[] Splitted = s.split(" ");
        int count = s.split(" ").length;
        int i = 0;
    
        String pass = "";
        boolean addFirstLetter = true;
        for(i = 0; i < count; i = i + 1) {
            pass += (addFirstLetter) ? Splitted[i].substring(0, 1) : Splitted[i].substring(Splitted[i].length() - 1);
            addFirstLetter = !addFirstLetter;
        }
    
        return count + pass;
    }
    
    public static void main(String[] args) {
        String pwd = pwdgen("Dies ist nur ein doofes Beispiel");
        System.out.println(pwd); // => "6Dtnndl"
        System.out.println(pwdgen("a b c")); // => 3abc
    }
    

    addFirstLetter will keep track of whether you're adding the first letter this loop or not, then the ternery operator ( ? : ) will add the correct letter to the string. Then the boolean is toggled to add the other letter in the next loop.