我试图读取一个文本文件,并且"加密" /将每个字母从ASCII表转换为+1(我也希望"解密"所以为-1)。所以" a"将成为" b"," b"到" c"等等。我只需要转换字母(忽略其他所有内容,按原样打印)。我对这段代码遇到了麻烦:
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) + " ");
}
我已经弄明白了如何为char添加+1,但我不确定如何将其添加回数组或正确打印出来(因为&#34; morewords.add(ch) )&#34;只会添加char,而不是转换所有字符添加字符串)。 &#34; words.get(i)。length()&#34;当我只想要字符串的长度@ position&#34; i&#34;时,取数组的整个长度&#34;单词&#34;在数组中,因此它会引发错误,因为数组的长度比字符串字长。我已经被困在这几个小时了,我无法理解。我想也许我不应该把它们作为字符串读出来,应该把它们作为字符读出来,这可能更简单了?
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");
}
}
答案 0 :(得分:2)
for循环中的第一个是正确的
for (int i = 0; i <= words.size()-1; i++){}
如果您从0开始,则以长度为1
结束我改变的是
PrintWriter fileOut = new PrintWriter("C:/Backwards.txt");
for (int i = 0; i <= words.size()-1; i++)
{
for (int j = 0; j <= words.get(i).length()-1; j++)
{
char ch = ' ';
ch = words.get(i).charAt(j);
ch ++; // +=1
morewords.add(ch);
fileOut.print(ch);
}
fileOut.print(" ");
}
fileOut.close();
如果我理解正确的话,它输出正确=)
这是我的代码
public static void main(String[] args) throws Exception
{
BufferedReader inChannel = new BufferedReader(new FileReader("C:/script.txt"));
BufferedWriter outChannel = new BufferedWriter(new FileWriter("C:/output.txt"));
String toParse = "";
while ( (toParse = inChannel.readLine()) != null )
{
String toWrite = "";
for(int i=0; i!=toParse.length();i++)
{
char c = toParse.charAt(i);
if(true) //check if must be encoded or not
{
c++;
toWrite += c;
}
}
outChannel.write(toWrite);
outChannel.newLine();
}
inChannel.close();
outChannel.close();
}
希望帮助