我只是一名初学程序员,我在这里找到我程序中的错误。该程序只读取我的文本文件中的大写字母,即使我的加密和解密方法中有一个小写的情况。我猜测它是caesarEncipher方法的一个问题。 (忽略我在主要方面的解读案例,我很快就会谈到它。)
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;
}
}
答案 0 :(得分:0)
在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))