我试图读取一个文本文件,并将每个字母“加密”/从ASCII表转换为+1(我也想“解密”,所以-1) 。所以“a”将变成“b”,“b”变成“c”等等。我只需要转换字母(忽略其他所有内容,按照原样打印)。我有麻烦与这部分代码:加密/解密文件。用于加密/解密的ASCII +1
我已经想通了如何+1炭,但我不知道如何添加回数组或打印出来正确(因为“morewords.add(ch)”只会添加字符,而不是转换所有的字符添加一个字符串)。 “words.get(i).length()”取整数组“words”的整个长度,当我只想将字符串@位置“i”的长度放在数组中时,它会抛出错误,因为长度数组的长度比字符串长。我一直坚持这几个小时,我无法弄清楚。我在想,也许我不应该以字符串的形式阅读它们,应该以字符的形式阅读它们,这可能会更简单?
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<String> words = new ArrayList<String>();
ArrayList<Character> morewords = new ArrayList<Character>();
String fileName = ""; //Replace Test with this
File f;
Scanner fileIn;
System.out.println("Please enter a file name for encryption: ");
//fileName = in.nextLine();
fileName = "Test.txt";
try
{
//Build the file and attach a scanner to it
f = new File (fileName);
fileIn = new Scanner (f);
System.out.println(f.exists()); //For errors
int counting = 0;
//Reads in indvidual strings.
for(counting =0; fileIn.hasNext(); counting++)
{
words.add(fileIn.next());
System.out.println(words);
}
PrintWriter fileOut = new PrintWriter ("Backwards.txt");
for(int i = 0; i <= words.size(); i++)
{
for(int j = 0; j <= words.get(i).length(); j++)
{
char ch = ' ';
ch = words.get(i).charAt(j);
ch += 1;
morewords.add(ch);
}
fileOut.print(morewords.get(i) + " ");
}
fileOut.close();
}
catch(FileNotFoundException e)
{
System.out.println("Couldn't find file");
}
}
基于安德烈的回答,这似乎是一个错字。是吗? – 2014-11-05 13:22:33