我的代码应该从文本文档中获取文本并通过将每个字符递增1来加密它。我希望输出为: qbttx (密码的加密。)但是它代替它只是输出: q 任何人都知道如何解决这个问题? 保存应加密内容的文本文档也包含文本“passw。”
import java.io.*;
public class EncryptionMain {
public static void main(String args[]) {
File file = new File("c:\\Visual Basic Sign in\\password.txt");
StringBuilder contents = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
contents.append(text)
.append(System.getProperty(
"line.separator"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
int first = 0, second = 1;
for (int i = 0; i < contents.length(); i++)
{
char[] arr = new char[7];
contents.getChars(first, second, arr, 0); // get chars 0,1 to get 1st char
char ch = arr[i];
if (ch >= 'A' && ch < 'Z') ch++;
else if (ch == 'Z') ch = 'A';
else if (ch >= 'a' && ch < 'z') ch++;
else if (ch == 'z') ch = 'a';
// show encrypted contents here
System.out.println(ch);
first++;
second++;
}
}
}
答案 0 :(得分:1)
contents.getChars(first, second, arr, 0);
char ch = arr[i];
这会将contents
中的字符复制到arr[0]
而不是arr[i]
。因此,将第二行更改为char ch = arr[0];
应该有效。但是有更简单的方法可以从String访问字符。参见'charAt'或'toCharArray'。