【问题标题】:Caesar Cipher in Java - printing blank lineJava中的Caesar Cipher - 打印空行
【发布时间】:2017-05-30 12:37:26
【问题描述】:

我目前正在尝试使用密钥 18 用 Ja​​va 编写凯撒密码。

到目前为止我的代码如下,但由于某种原因我无法解决,它不起作用。

import java.util.Objects;
import java.util.Scanner;
class MainApplication {
private static final Scanner input = new Scanner(System.in);

private static String CryptMessage(int key, String message) {
    StringBuilder temp = new StringBuilder();
    for (int i = 0; i == message.length(); i++) {
        if (Character.isLetter(message.charAt(i))) {
            int num = (int) message.charAt(i);
            num = num + key;
            if (Character.isUpperCase(message.charAt(i))) {
                if (num > (int) ('Z')) {
                    num = num - 26;
                } else if (num < (int) ('A')) {
                    num = num + 26;
                }
            }
            if (Character.isLowerCase(message.charAt(i))) {
                if (num > (int) ('z')) {
                    num = num - 26;
                } else if (num < (int) ('a')) {
                    num = num + 26;
                }
            }
            temp.append((char) num);
        } else {
            temp.append(message.charAt(i));
        }
    }
    message = temp.toString();
    return message;
}
private static void encrypt(){
    int key = 18;
    System.out.println("Please enter a message to encrypt: ");
    String message = input.nextLine();
    System.out.println(CryptMessage(key, message));
}
private static void decrypt(){
    int key = -18;
    System.out.println("Please enter a message to decrypt: ");
    String message = input.nextLine();
    System.out.println(CryptMessage(key, message));
}
public static void main(String args[]){
    System.out.println("Message Encryption System 3.0");
    System.out.println("Please select an option:");
    System.out.println("[1] - Encrypt Message");
    System.out.println("[2] - Decrypt Message");
    String opt = input.nextLine();
    if(Objects.equals(opt, "1")){
        encrypt();
    }
    else if(Objects.equals(opt, "2")){
        decrypt();
    }
    else{
        System.out.println("Invalid input.");
    }
}
}

程序运行,但是,它会在加密(或解密)消息所在的位置打印一个空白行。

【问题讨论】:

  • 您是否打算这样做 --> i == message.length(); 作为您的 for 循环条件?应该是i &lt; message.length();
  • 这对我来说也很奇怪
  • 问题是 CryptMessage 返回一个空字符串,因为根本不满足 for 循环条件(因此不会执行 for 循环内的任何语句),即使它满足了,你' d 得到一个StringIndexOutOfBoundsException
  • 我的错误,我已经纠正了,现在可以正常使用了

标签: java console-application caesar-cipher


【解决方案1】:

循环条件i == message.length() 应该是i &lt; message.length()

for 循环中的条件确定何时继续下一次迭代。您的条件在第一次迭代时为假,循环立即终止(在第一次迭代之后)。

【讨论】:

    【解决方案2】:

    这是一个可以用调试器解决的问题。如果您一次浏览一行代码,则更容易发现 nimrodm 指出的循环条件未按您期望的方式执行这一事实。此外,您可以在执行过程中检查变量的值,并确保它们在每一步都是正确的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-06
      • 1970-01-01
      • 2017-03-25
      • 1970-01-01
      相关资源
      最近更新 更多