java - 如何按给定顺序返回数组元素?

标签 java c arrays password-generator

我的功能是密码生成器。它选择句子中的单词数量。并交替获取第一个字母和最后一个字母。示例在 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
}

最佳答案

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

return count + firstChar + lastChar;

在你的for循环中;不要将它们添加到两个单独的字符串中,而是将它们添加到同一个字符串中。不过,您需要保留一个 boolean 值来检查是否添加第一个字母或最后一个字母。

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

关于java - 如何按给定顺序返回数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58441481/

相关文章:

java - hadoop version命令给出与Java相关的错误(无此文件或目录)

java - LogCat条目含义

java - 如何检测一个旋转窗口是否在另一个旋转窗口上方

c - c中的静态变量

c - 在 C 编程中,如何使用循环询问用户是否要继续?

Java 包。每个文件不能使用多个包

c - 在 C 中填充二维数组

arrays - 快速制作一个数组数组

arrays - 如何在 MATLAB 中创建规则间隔的值数组?

arrays - 如何使用 SlowCheetah 转换 Json 配置文件中的数组元素?