0

我的功能是密码生成器。它选择句子中单词的数量。并交替取第一个字母和最后一个字母。示例在 void main 方法中。

我的问题是我不知道如何旋转 firstChar 和 lastChar。我在 if 语句中用模数尝试了它,但没有让我更进一步。也许你们有一些想法。

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
}
4

1 回答 1

1

当您在密码生成器中返回字符串时;您将返回所有第一个字母 - 然后是所有最后一个字母:

return count + firstChar + lastChar;

在你的 for 循环中;与其将它们添加到两个单独的字符串中,不如将它们添加到一个相同的字符串中。不过,您需要保留一个布尔值来检查您是添加第一个字母还是最后一个字母。

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 将跟踪您是否在此循环中添加第一个字母,然后三元运算符 ( ? : ) 会将正确的字母添加到字符串中。然后切换布尔值以在下一个循环中添加另一个字母。

于 2019-10-17T22:55:10.197 回答