【问题标题】:Caesar cipher in Java ACMJava ACM 中的凯撒密码
【发布时间】:2013-12-30 14:12:35
【问题描述】:

我在使用 ACM 的 Java 中使用凯撒密码时遇到问题。这是我的代码:

import acm.program.*;

public class Ceasar extends ConsoleProgram{

  public void run() {
    println("This program encodes a
    message using a Caesar cipher.");

    int shifter=readInt("Enter the number of character positions to shift: ");
    String msg=readLine("Enter a message :");
    String Solution=encodeCaesarCipher(msg,shifter);

    println("Encoded message: "+Solution);
  }

  private String encodeCaesarCipher(String str,int shift){
    String result="";

    for (int i=0;i<str.length();i++){
      char helper=str.charAt(i);
      helper=(helper+shift);

      if (helper>'Z'||helper>'z') helper =(helper-26);
      if (helper<'A'||helper<'a') helper=(helper+26);

      result= result+helper;
    }

    return result;
  }
}

编译时出现以下错误:

Ceasar.java:21: error: possible loss of precision
  helper=helper+shift;
                ^
  required: char
  found: int

Ceasar.java:22: error: possible loss of precision
  if (helper>'Z'||helper>'z') helper =helper-26;
                                             ^
  required: char
  found: int

Ceasar.java:23: error: possible loss of precision
  if (helper<'A'||helper<'a') helper=helper+26;
                                            ^
  required: char
  found: int
3 errors

【问题讨论】:

  • 请始终拼写 Caesar,还有什么问题?

标签: java acm-java-libraries


【解决方案1】:

您不能在 Java 中将 int 添加到 char 中,除非您明确表示您同意可能的精度损失(上溢/下溢)。将(char) 演员表添加到intchar 一起使用的每个地方。

【讨论】:

    【解决方案2】:

    这是您的代码的固定版本。
    将其与您的版本进行比较以确保
    你了解这些变化。

        public static void main(String[] args){
            String s = encodeCaesarCipher("abc", 5);
            System.out.println(s);
            s = encodeCaesarCipher("abc", 2);
            System.out.println(s);
            s = encodeCaesarCipher("abc", 1);
            System.out.println(s);
        }
    
        private static String encodeCaesarCipher(String str,int shift){
             String result="";
             for (int i=0;i<str.length();i++){
                 int helper=str.charAt(i);
                 helper=(helper+shift);
                 if (helper>'Z'||helper>'z') helper =(helper-26);
                 if (helper<'A'||helper<'a') helper=(helper+26);
                    result= result+ (char)helper;
             }
             return result;
         }
    

    输出:

    fgh
    cde
    bcd
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-07
      相关资源
      最近更新 更多