【问题标题】:Creating a cipher, but returning error创建密码,但返回错误
【发布时间】:2016-02-06 14:31:04
【问题描述】:

我正在尝试制作一个密码,您在其中输入一个单词,它会根据用户选择的任何内容进行转换,但我收到此错误:

线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:2
在 java.lang.String.charAt(未知来源)
在 cipher.mycipher.main(mycipher.java:24)

我不确定为什么会收到此错误?

这是我的代码:

public class mycipher {

    public static void main(String[] args) {
        int[] storagelocation = new int[25];
        char[] letter1 = new char[25];
        char[] init = new char[25];
        Scanner consolereader = new Scanner(System.in);
        char[] letters = {'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'};
        System.out.println("what word would you like to cipher?");
        String original = consolereader.nextLine();
        System.out.println("how much would you like to shift it by");
        int shift = consolereader.nextInt();

        for (int i = 0; i < 25; i++) {
            storagelocation[i] = i;
            letter1[i] = letters[i];
            if (letter1[i] == (original.charAt(i))) {
                letter1[i] = init[i];
            }
        }
        System.out.println(Arrays.toString(init));
    }
}

【问题讨论】:

  • 因为你没有给它一个 25 个字符的输入。错误信息很清楚,调试器会解释更多
  • 调试器没有帮助。将所有数字 25 更改为 26,在线程“main”中出现此错误异常 java.lang.StringIndexOutOfBoundsException: String index out of range: 5 at java.lang.String.charAt(Unknown Source) at cipher.mycipher.main(mycipher .java:24)
  • 您知道,您的代码不会担心输入的长度,对吧?如果它的长度不是至少 25(或 26)个字符,它就会失败。
  • @JoshInttap String original = consolereader.nextLine(); -- 这里是减少的长度,而不是数组。如果输入 4-char 输入,那么应该从 0 迭代到 3,而不是 24。
  • @xoce 请不要在帖子中突出显示正常测试。将 "Here is my code:" 编辑成粗体文本绝对没有任何价值。

标签: java caesar-cipher


【解决方案1】:

你必须添加类似的条件

 for (int i= 0; i < original.length(); i++) {
            storagelocation[i] = i;
            letter1[i] = letters[i];
            if (letter1[i] == original.charAt(i)) {
                letter1[i] = init[i];
            }
 }

不要超过原来的长度,否则 for 循环将迭代到 25。

【讨论】:

    【解决方案2】:

    执行的迭代应该基于原始的长度而不是25。

    你在循环中的逻辑看起来很混乱。如果你解释清楚,我可以试着给你工作代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 2011-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多