使用密码表对字符串进行编码

huangapple go评论100阅读模式
英文:

Encoding string using cipher table

问题

我需要使用给定的 cipherTable 和给定的 key 对给定的 message 进行编码。我相当确定 encode 方法存在问题,但我不确定具体是什么问题。以下是代码:

import java.util.ArrayList;

public class Prog3Cipher {
    // 实例变量
    static char[] keyList; // 变量描述注释
    static char[][] cipherTable; // 变量描述注释
    String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    static String encode(String message) {
        String result = "";
        ArrayList<Character> w = new ArrayList<>();
        String[] m = new String[]{message};
        for (int p = 0; p < m.length; p++) {
            int row = Character.getNumericValue(keyList[p]);
            int column = Character.getNumericValue(Integer.parseInt(m[p]));
            char q = cipherTable[row][column];
            w.add(q);
        }
        result = String.join(" ", (CharSequence) w);
        return result;
    }

    public Prog3Cipher(char code, String key) {
        keyList = key.toCharArray();
        int offset = code - 'A';
        cipherTable = new char[26][26];
        for (int x = 0; x < cipherTable.length; x++) {
            for (int y = 0; y < cipherTable[0].length; y++) {
                cipherTable[x][y] =
                        alpha.charAt((x + y + offset) % alpha.length());
            }
        }
    }

    public static void main(String[] args) {
        // 仅在使用 VM 参数 -ea 时才能正常运行测试
        Prog3Cipher self = new Prog3Cipher('H', "BABBAGE");
        assert "PHXXF MQYBPKNJ".equals(self.encode("Happy Birthday"));
    }
}

输出:

Exception in thread "main" java.lang.NumberFormatException: For input string: "Happy Birthday"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at Prog3Cipher.encode(Prog3Cipher.java:24)
at Prog3Cipher.main(Prog3Cipher.java:68)
Process finished with exit code 1

encode 方法接收一个密码表 cipherTable,并找到 rowcolumn 的交点,这些交点分别由 keyListm 找到,交点的值被赋给 q,然后添加到 ArrayList w 中。result 被设置为一个字符串并返回。

我不确定具体问题在哪,因为代码中没有出现错误。如果有人能够检查一下并给予一些指导,将不胜感激。

英文:

I need to encode a given message using cipherTable and a given key. I'm pretty sure there's something wrong with the encode method but i'm not sure what. This code:

import java.util.ArrayList;

public class Prog3Cipher {
    // INSTANCE VARIABLES
    static char[] keyList; // VARIABLE DESCRIPTION COMMENT
    static char[][] cipherTable; // VARIABLE DESCRIPTION COMMENT
    String alpha = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;;

    static String encode(String message) {
        String result = &quot;&quot;;
        ArrayList&lt;Character&gt; w = new ArrayList&lt;&gt;();
        String[] m = new String[]{message};
        for (int p = 0; p &lt; m.length; p++) {
            int row = Character.getNumericValue(keyList[p]);
            int column = Character.getNumericValue(Integer.parseInt(m[p]));
            char q = cipherTable[row][column];
            w.add(q);
        }
        result = String.join(&quot; &quot;, (CharSequence) w);
        return result;
    }

    public Prog3Cipher(char code, String key) {
        keyList = key.toCharArray();
        int offset = code - &#39;A&#39;;
        cipherTable = new char[26][26];
        for (int x = 0; x &lt; cipherTable.length; x++) {
            for (int y = 0; y &lt; cipherTable[0].length; y++) {
                cipherTable[x][y] =
                        alpha.charAt((x + y + offset) % alpha.length());
            }
        }
    }

    public static void main(String[] args) {
        // Testing only works if using VM argument -ea
        Prog3Cipher self = new Prog3Cipher(&#39;H&#39;, &quot;BABBAGE&quot;);
        assert &quot;PHXXF MQYBPKNJ&quot;.equals(self.encode(&quot;Happy Birthday&quot;));
    }
}

Output:

Exception in thread &quot;main&quot; java.lang.NumberFormatException: For input string: &quot;Happy Birthday&quot;
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at Prog3Cipher.encode(Prog3Cipher.java:24)
at Prog3Cipher.main(Prog3Cipher.java:68)
Process finished with exit code 1

the encode method takes a cipher table, cipherTable, and finds the intersection point of the row and column, which are found with keyList and m, and the intersection is set to q and then added to an Arraylist w. Result is set to a String and returned.

i'm not sure what's wrong as there are no errors with the code so if anyone could look over it and give some guidance it would be much appreciated.

答案1

得分: 1

这一行很可能是问题的根源。

int column = Character.getNumericValue(Integer.parseInt(m[p]));

NumberFormatException 来自于 Integer.parseInt()。如果你检查 m

,你会发现它是一个长度为1的数组,其中 m[0]="Happy Birthday"。字符串 "Happy Birthday" 无法被解析为数字,因此出现了异常。

如果你想将一个字符串拆分为单独的字符,你可以使用 String.toCharArray(),像这样:char[] m = message.toCharArray();

你的代码中还有一些其他问题:

  • main() 方法中创建了一个 Prog3Cipher 的实例,但 encode() 是静态的,所以对 self.encode() 的调用可能不会按预期工作。从 encode() 方法的声明中移除 static 应该可以解决这个问题。
  • Character.getNumericValue() 返回所提供字符的 Unicode 值。该方法对于 'A' 返回 10,对于 'Z' 返回 35,因此这些值与你的 cipherTable 数组的范围不匹配。
  • 如代码所写,encode() 中的 for 循环将超过 keyList[] 数组的末尾。这是因为 keyList[] 只有 7 个字符,而 message 中有 14 个字符。
  • encode() 方法对于 message 中的空格没有进行特殊处理,因此它们很可能也会引发异常。
英文:

This line is the likely culprit.

int column = Character.getNumericValue(Integer.parseInt(m

));

The NumberFormatException is from the Integer.parseInt(). If you inspect m

you'll find that it is an array of length 1 with an where m[0]=&quot;Happy Birthday&quot;. The String "Happy Birthday" can't be parsed as a number, thus the exception.

If you want to break a String into its individual characters, you could use String.toCharArray() like this: char[] m = message.toCharArray();

There are some other issues in your code:

  • In the main() method an instance of Prog3Cipher is being created, but encode() is static, so the call to self.encode() likely isn't working as you might expect. Removing static from the method declaration of encode() should fix that problem.
  • Character.getNumericValue() returns the unicode value of the provided character. That method returns 10 for 'A' through 35 for 'Z', so the values don't match the bounds of your cipherTable array.
  • As written, the for loop in encode() will walk past the end of the keyList[] array. This is because keyList[] only has 7 characters compared to the 14 chars in message.
  • The encode() method doesn't have any special handling for spaces in message, so they'll most likely also cause an exception.

huangapple
  • 本文由 发表于 2020年9月28日 05:53:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/64093668.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定