在Java Caesar Cipher中保留空格,标点符号和char个案

时间:2015-10-08 17:33:07

标签: java arrays char uppercase caesar-cipher

我正在尝试加密txt文件,但是当我将我的字符发送到数组时,我会失去空间。我想保留我的空格以及标点符号和字母。我是如此接近,但似乎无法做任何不做A.的事情。)一切都是空字符或B.)循环大写字母。提前谢谢。

public class Encryption {
     CaesarCipher c= new CaesarCipher();
     Scanner kb = new Scanner(System.in);
     String end = "";

public void changeLetters(File file) {
    System.out.println("How far would you like to shift?");
    int shift = Integer.parseInt(kb.nextLine());
    Scanner fileScanner;
    try {
        fileScanner = new Scanner(file);
        while (fileScanner.hasNextLine()) {
            String line = fileScanner.nextLine();
            shift(line, shift);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

private void shift(String line, int shift) {
    char[] og = line.toCharArray();
    for (int i = 0; i < og.length; i++) {
        char letter = og[i];
        letter = (char) (letter + shift);
        if (letter > 'z') {
            letter = (char) (letter - 26);
        } else if (letter < 'a') {
            letter = (char) (letter + 26);
        }
        end = end + Character.toString(letter);
    }
    System.out.println(end);

    File file = new File("Encrypted.txt");
    FileWriter writer = null;

    {
        try {
            writer = new FileWriter(file);
            writer.write(end);
            writer.close();
        } catch (

        IOException e)

        {
            e.printStackTrace();
        }
        System.out.println("Decryption Complete");
        System.out.println("Q to quit, C to Continue");
        String response = kb.next();
        if (response.equals("q") || response.equals("Q")) {
            System.out.println("Goodbye");
        } else if (response.equals("c") || response.equals("C")) {
            c.getInformation();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我认为问题来自你在信件中添加(+/-)26的事实,例如letter = (char) (letter - 26);。这只适用于字母[a-z]。但是,由于您希望能够处理大写字母,特殊字符等,因此您无法执行此操作。

使用模运算符%来执行此操作也会更清晰。因此,您不必像if (letter > 'z')那样进行明确的测试。

这是转移程序,非常简单

private String shift(String str, int shift) {
    String shifted = "";
    for(int i = 0; i < str.length(); i++) {
        char original = str.charAt(i);
        char shiftedChar = (char) ((original + shift) % Integer.MAX_VALUE);
        shifted += shiftedChar; // Append shifted character to the end of the string
    }

    return shifted;
}

但是我不确定这是使用的模数。但我做了一些测试,这似乎有效。

以下是你如何转换和取消

String test = "This is a test!";
String encoded = shift(test, 3);
String decoded = shift(encoded, -3);

System.out.println("Encoded : " + encoded + "\n" + "Decoded : " + decoded);
相关问题