我正在尝试读取一个文本文件,并将每个字母的“加密”/convert从ASCII表中“加密”到+1 (我还希望“解密”so -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) + " ");
} 我已经知道了如何将这个字符+1添加到数组中,但我不确定如何将它添加回数组或正确地打印出来(因为"morewords.add(ch)“只会添加这个字符,而不是将所有字符转换为一个添加字符串)。"words.get(i).length()“获取数组”word“的整个长度,当我只想要字符串@位置"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:20:54
在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();如果我理解了right =,它就会输出。)
这是我的密码
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();
}希望帮了忙
https://stackoverflow.com/questions/26751006
复制相似问题