Java中的Caesar代码
我正试图写一个凯撒代码程序,对代码进行解码和编码。 它将接收一个文件并返回一个解码或编码文件 以下是我写的:Java中的Caesar代码,java,Java,我正试图写一个凯撒代码程序,对代码进行解码和编码。 它将接收一个文件并返回一个解码或编码文件 以下是我写的: import java.io.*; import java.util.Scanner; public class cc { public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException { System.out.println("Welc
import java.io.*;
import java.util.Scanner;
public class cc
{
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException
{
System.out.println("Welcome to CaesarCipher");
System.out.print("Enter 1 to encipher, or 2 to decipher (-1 to exit) ");
Scanner scan = new Scanner(System.in);
int answer = scan.nextInt();
System.out.print("What non-negative shift should I use? ");
Scanner scan1 = new Scanner(System.in);
int i = scan1.nextInt();
System.out.print("What is the input file name? ");
Scanner scan2 = new Scanner(System.in);
String file = scan2.nextLine();
System.out.print("What is the output file name? ");
Scanner scan3 = new Scanner(System.in);
String savefile = scan3.nextLine();
if (answer == 1)
{
encode(file, savefile, i);
} else if ( answer == 2)
{
decode(file, savefile, i);
} else if ( answer == -1)
{
System.out.println("See you later, aligator!");;
}
System.out.println("DONE!");
}
public static void encode(String file, String savefile, int i) throws FileNotFoundException, UnsupportedEncodingException
{
File f2 = new File(savefile);
PrintWriter writer = new PrintWriter(f2, "UTF-8");
i = i % 26 + 26;
File f = new File(file);
Scanner input = new Scanner(new FileInputStream(f));
StringBuilder encoded = new StringBuilder();
for (char y : file.toCharArray())
{
if (Character.isLetter(y))
{
if (Character.isUpperCase(y))
{
encoded.append((char) ('A' + (y - 'A' + y) % 26 ));
} else
{
encoded.append((char) ('a' + (y - 'a' + y) % 26 ));
}
} else
{
encoded.append(y);
}
writer.print(encoded.toString());
}
writer.close();
}
public static void decode(String file, String savefile, int i) throws FileNotFoundException, UnsupportedEncodingException
{
encode(file, savefile, 26-i);
}
}
然而,问题是输出文件总是空的。
我的代码有什么问题
[编辑]
您好,我添加了writer.close()代码>但我仍然有一个问题
当我输入奶牛正在割草时,输入文件中的每个人都很高兴
,移位为2,它会给我输出
**hhbhbphbpphbppvhbppv.hbppv.fhbppv.fnhbppv.fnf**
这是正确的吗
谢谢您需要关闭PrintWriter流
writer.close();
首先,将write语句放在编码循环结束后:
for (char y : ...
...
}
writer.print(encoded.toString());
writer.close();
其次,不能使用文件名(!)访问文件数据:
file.toCharArray()
返回包含输入文件名字符的字符数组。逐个读取文件:
File f = new File(file);
FileInputStream is = new FileInputStream(f);
StringBuilder encoded = new StringBuilder();
int y;
while( (y = is.read()) != -1 ){
// ...
}
调用writer.close()
在writer.print()
@BoDidely嗨,我编辑了我的问题。你能看一下吗。在提问时不要移动目标。如果你不断改变问题的内容,答案就会变得无关紧要,网站的工作方式也会有点分崩离析。你能告诉我们输入文件的名称吗?@JohnSmith没问题。。。如果您在解决了原来的问题后还有其他问题,当然欢迎您发布新问题。您好,我编辑了我的问题。你能看一下吗。Thanks@JohnSmith这是凯撒班次的预期产量吗?如果您需要验证,请使用传统的纸笔方法。@JohnSmith如果我回答了您最初的问题,请单击论坛上其他开发人员答案旁边的不透明复选标记。