Caesar Cipher with Java Code - 将只读取大写



我只是一个初级程序员,我来这里是为了在我的程序中发现一个错误。该程序只读取我的文本文件中的大写字母,即使我的加密和解密方法中有小写字母。我猜这是凯撒加密方法的问题。(主要忽略我的破译案例,我很快就会谈到它。

import java.util.*;
import java.io.*;
public class Cipher {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to CaesarCipher");
System.out.println();
System.out.println("Enter 1 to Encipher, 2 to Decipher, or -1 to exit");
int choice = 0;
do {
choice = scan.nextInt();
if (choice == 1) {
System.out.println("What non-negative shift should be used?");
int shift = scan.nextInt();
System.out.println("What is the input file name?");
String input = scan.next();
System.out.println("What is the output file name?");
String output = scan.next();
System.out.println(caesarEncipher(input, shift, output));
} else if (choice == 2) {
} else if (choice == -1) {
System.out.println("Thank you for using CaesarCipher");
break;
}
} while (choice != 1 && choice != 2 && choice != -1);
}
public static String caesarEncipher(String inputString, int shift, String output) throws FileNotFoundException {
File outFile = new File(output);
PrintStream encoded = new PrintStream(outFile);  // creates new file for the output
File input = new File(inputString);  // creates file with String to scan
Scanner scan = new Scanner(input); // creates Scanner
while (scan.hasNextLine()) {
String cipher = scan.nextLine();            // gets next line of file
String encipher = "";                   // String to be added to new file
int i;
for (i = 0; i < cipher.length(); i++) {
String curr = cipher.substring(i, i + 1);  // current character
String newChar = encrypt(curr, shift);
encipher = encipher + newChar;
}
encoded.println(encipher);
}
encoded.close();
return "DONE";
}
public static String encrypt(String str, int shift) {
String encrypted = "";
for (int i = 0; i < 1; i++) {
int c = str.charAt(i);
if (Character.isUpperCase(c)) {//if uppercase
c = c + (shift % 26);
if (c > 'Z') { //resets if it passes 'Z'
c = c - 26;
} else if (Character.isLowerCase(c)) {// if lowercase
c = c + (shift % 26);
if (c > 'z') { // resets if it passes 'z'
c = c - 26;
}
}
encrypted = encrypted + (char) c; // adds the encrypted character to the string
}
}
return encrypted;
}
public static String decrypt(String str, int shift) {
String decrypted = "";
for (int i = 0; i < 1; i++) {
int c = str.charAt(i);
if (Character.isUpperCase(c)) //if uppercase
{
c = c + (shift % 26);
if (c < 'A') { //resets if it passes 'A'
c = c + 26;
}
} else if (Character.isLowerCase(c)) // if lowercase
{
c = c + (shift % 26);
if (c < 'a') { // resets if it passes 'a'
c = c + 26;
}
}
decrypted = decrypted + (char) c; // adds the derypted character to the string
}
return decrypted;
}
}

encrypt()方法中: 这部分代码

else if(Character.isLowerCase(c)) {
c=c+(shift%26);
if(c>'z') { 
c=c-26;
}
}
encrypted=encrypted+(char)c; 

属于if(c>'Z')而不是if(Character.isUpperCase(c))

最新更新