【发布时间】:2015-03-05 03:31:43
【问题描述】:
我对我编写的程序正在输出的东西感到非常困惑。该程序的目的是解码/编码为一种称为 Caesar Shift 的代码,它基本上只是获取单词/句子的每个字母并通过“移位键”将其向右移动。 (例如 ab 与 shift 键 1 = bc)。
我已经设置了程序,以便它询问用户加密/解密,然后是他们想要编码/解码的消息,然后是 shift 键。我的两个编码/解码功能都有同样的问题。我将专注于这个问题的编码,因为它们几乎相同。
基本上,我设置了编码函数,以便它接受字符串消息和 int ShiftKey 的参数。我有一个消息的每个单独字母的字符串数组。我的计划是遍历数组/单词中的每个字母,找到它在字母表中的当前索引,并将 shift Key 添加到它,它存储在 int finalIndex 中。我在索引 finalIndex 处附加字母表的字母,最后打印该单词。
public static void encode(String message, int shiftKey)
{
String [] array = message.split("");
String encoded = "";
for (String a : array)
{
int finalIndex;
int index = alphabet.indexOf(a);
finalIndex = index + shiftKey;
encoded += alphabet.charAt(finalIndex);
}
System.out.println(encoded);
}
问题是,当我运行程序时,输出是正确的,除了在编码短语的开头,总是有一个额外的字母,即 shiftKey 处的字母表索引。 例如,如果我使用 shift 键 1 键入消息“hi”,那么它会输出“bij”,因为 b 是索引 1 处的字母,而 hi 只是预期的移位。
我已经尝试了所有方法,但我无法弄清楚为什么会发生这种情况。我确定这是此功能的问题,而不是其他任何地方,因为我尝试隔离不同的区域以查看问题所在。
任何帮助将不胜感激。谢谢。
完整代码
import java.util.*;
import java.io.*;
public class CaesarShiftTester
{
public static void main (String[] args)
{
boolean running = true;
while (running){
Scanner in = new Scanner (System.in);
System.out.println("Encryption or Decryption? (E/D): " );
String answer = in.next();
if (answer.equalsIgnoreCase("e"))
{
System.out.println("Enter message: ");
String message = in.next();
System.out.println("Enter Shift Key: " );
int shiftKey = in.nextInt();
CaesarShiftEncryption.encode(message, shiftKey);
System.out.println("Quit? (Y/N): ");
String again = in.next();
if (again.equalsIgnoreCase("Y"))
running = false;
else
running = true;
}
else if (answer.equalsIgnoreCase("d"))
{
System.out.println("Enter message: ");
String message = in.next();
System.out.println("Enter Shift Key: " );
int shiftKey = in.nextInt();
CaesarShiftEncryption.decode(message, shiftKey);
System.out.println("Quit? (Y/N): ");
String again = in.next();
if (again.equalsIgnoreCase("Y"))
running = false;
else
running = true;
}
}
}
}
\
import java.io.*;
import java.util.*;
public class CaesarShiftEncryption
{
private static final String alphabet = "abcdefghijklmnopqrstuvwxyz";
public static void encode(String message, int shiftKey)
{
String [] array = message.split("");
String encoded = "";
for (String a : array)
{
System.out.println(a);
int finalIndex;
int index = alphabet.indexOf(a);
finalIndex = index + shiftKey;
System.out.println(finalIndex);
encoded += alphabet.charAt(finalIndex);
}
System.out.println(encoded);
}
public static void decode(String message, int shiftKey)
{
char shifted;
String encoded = "";
for (int i = 0; i < message.length(); i ++)
{
char nextChar = message.charAt(i);
shifted = (char)(nextChar - shiftKey);
encoded += shifted;
}
System.out.println("Encoded: " + encoded);
}
}
【问题讨论】:
-
当我打印出数组的内容时,输出很好,它会按原样打印消息的每个字母,但是当我打印出最终索引时,它会打印出 shiftkey,然后正确的最终索引,因此它比应有的多一个。
-
我测试了你的代码,它可以正常工作。您可能对消息有问题
-
我无法重现该问题...如果我用键 1 输入“hi”,我会得到“ij”...
-
您的代码对我有用,我没有看到任何额外的字母...这是输出:加密还是解密? (E/D): e Enter message: hi Enter Shift Key: 1 h 8 i 9 ij
标签: java