【问题标题】:How to loop back to the beginning of a table [java] [duplicate]如何循环回到表的开头[java] [重复]
【发布时间】:2020-12-03 19:04:40
【问题描述】:

我需要写一条消息,然后按照一定的数字将每个字母更改为另一个

例如:如果我的消息是 abcd 并且选择的数字是 5,那么我的消息必须变成 fghi。

我只是创建了一个遍历表 char 的 for 循环,并创建了一个包含所有字母表和每个字母的 switch case。我认为这就像 python,我可以循环到表的开头,但它告诉我索引超出了范围。我的可能性是什么?

char[] abc = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
        for (int i = 0; 1 <= mesgIn.length; i++){
            switch(mesgIn[i]) {
                case 'a' -> mesgIn[i] = mesgIn[rot];
                case 'b' -> mesgIn[i] = abc[1 + rot];
                case 'c' -> mesgIn[i] = abc[2 + rot];

编辑:int rot 是我想要做的字母旋转次数。等于用户想要的wtv

编辑 2:发现更容易做到这一点。我只是在 abc[] 中添加了两次字母,所以 abc[0] 是 'a',但 abc[26] 也是如此

【问题讨论】:

    标签: java arrays indexing message


    【解决方案1】:

    索引从String 中的0 开始,因此最后一个索引是字符串长度减去1。因此,循环的终止条件应该是i &lt; mesgIn.length()。此外,您可以使用 char 值执行算术运算,就像使用 int 值一样。

    public class Main {
        public static void main(String args[]) {
            char[] abc = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
                    't', 'u', 'v', 'w', 'x', 'y', 'z' };
            String mesgIn = "wxyz";
            int n = 5;
            for (int i = 0; i < mesgIn.length(); i++) {
                System.out.print((char) ((mesgIn.charAt(i) - 'a' + n) % 26 + 'a'));
            }
        }
    }
    

    输出:

    bcde
    

    【讨论】:

    • 但假设我想将 z 转换为 e。我该如何进行?
    • @Avunz - 检查更新的答案。
    • 非常感谢!这绝对有帮助
    【解决方案2】:

    您还可以使用一些标准数据结构和定义明确的方法。

    import java.util.Arrays;
    import java.util.List;
    
    public class Main {
      public static void main(String[] args) {
        String[] messages = {"abc", "xyz"};
        int rot = 5;
        List<Character> alphabets =
            Arrays.asList(
                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
                'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
        for (String message : messages) {
          for (int i = 0; i < message.length(); i++) {
            char originalChar = message.charAt(i);
            int indexInAlphabets = alphabets.indexOf(originalChar);
            System.out.print(alphabets.get((rot + indexInAlphabets) % alphabets.size()));
          }
          System.out.print("\n");
        }
      }
    }
    

    输出

    fgh
    cde
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-13
      • 1970-01-01
      • 1970-01-01
      • 2013-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多