【问题描述】Julius Caesar(凯撒)加密方法。该方法在每次加密时都选定一个加密密钥,它是一个1到25之间的数字,用于指定加密字母时的移位个数。例如,如果密钥为3,则将A转换为D,将Z转换为C,依次类推。小写字母亦如此(参见下图),其它字符不变。用该方法对文件加密。提示:若密钥为key,则对大写字母来说,转换公式为‘A’+ ( c - ‘A’ + key ) % 26。
M | E | e | t | m | e | a | t |
P | H | h | w | p | h | d | W |
【输入形式】从标准输入中输入一个1到25之间的整数作为密钥,然后读取当前目录下的文件in.txt,该文件含有多行任意字符,也可能有空行。每个文本行最长不超过80个字符。
【输出形式】对输入文件内容按上述方法进行加密后输出到当前目录下文件out.txt中。
【样例输入】若输入密钥为3, in.txt文件内容如下:
c language is important.
WO AI BEIJING TIANANMEN.
YYH SZ DSZ DDSZ.
【样例输出】加密后out.txt文件内容如下:
f odqjxdjh lv lpsruwdqw.
ZR DL EHLMLQJ WLDQDQPHQ.
BBK VC GVC GGVC.
【样例说明】根据输入密钥和转换公式对输入文件的内容进行加密,并将结果输出到文件out.txt中。
参考代码一:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int k=sc.nextInt();
BufferedReader ifile = new BufferedReader(new FileReader("in.txt"));
BufferedWriter ofile = new BufferedWriter(new FileWriter("out.txt"));
String s = null;
while((s = ifile.readLine())!=null) {
String ss1="";
for(int i=0;i<s.length();i++) {
char ch = s.charAt(i);
if(Character.isUpperCase(ch)) {
ss1 += ((char)('A'+ (ch-'A' + k)%26)+"");
}else if(Character.isLowerCase(ch)) {
ss1 += ((char)('a'+ (ch-'a' + k)%26)+"");
}else {
ss1+=(ch+"");
}
}
ofile.write(ss1);
ofile.newLine();
}
ofile.close();
ifile.close();
}
}
参考代码二:
import java.io.*;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
BufferedReader ifile = new BufferedReader(new FileReader("in.txt"));
BufferedWriter ofile = new BufferedWriter(new FileWriter("out.txt"));
int key = sc.nextInt();
String str;
while((str = ifile.readLine())!=null) {
for(int i=0;i<str.length();i++) {
char ch = str.charAt(i);
if(ch>='a'&&ch<='z') {
ofile.write( (char)('a'+ ( ch - 'a' + key ) % 26));
}
else if(ch>='A'&&ch<='Z') {
ofile.write((char)('A'+ ( ch - 'A' + key ) % 26));
}
else {
ofile.write(ch);
}
}
ofile.newLine();
}
ofile.close();
ifile.close();
sc.close();
}
}