|
I've written the following code...The encrypt() method is supposed to read text from a file and encode it by shifting each letter three to the right. Decrypt() is supposed to decrypt in a similar way, by shifting each letter three to the left. The encrypt() method works just fine, and the decrypt() almost works...Instead of returning 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' when I enter the appropriate encoded string, it returns 'ABCDEFGHIJKLMNOPQRSTUVW>?@'
protected void encrypt(String ipfile, String opfile) throws IOException
{
StringBuffer contents = new StringBuffer();
StringBuffer newContents = new StringBuffer();
BufferedReader input = null;
Writer output = null;
char letter, newLetter;
int uni, answer;
try
{
input = new BufferedReader(new FileReader(ipfile) );
String line = null;
output = new BufferedWriter( new FileWriter(opfile) );
while ((line = input.readLine()) != null)
{
contents.append(line);
for (int i = 0; i < contents.length(); i++)
{
letter = contents.charAt(i);
uni = (int)letter;
if (uni == 32)
{
answer = 32;
}
else if (uni == 13)
{
answer = 13;
}
else
{
answer = (((uni - 65) + 3)%26) + 65;
}
newLetter = (char)answer;
newContents.append(newLetter);
}
newContents.append(System.getProperty("line.separator"));
contents.delete(0, contents.length());
}
String newContentString = newContents.toString();
output.write(newContentString);
}
catch (IOException e)
{
System.out.println("I/O Error: " + e.getMessage());
System.exit(1);
}
finally
{
if (output != null) output.close();
}
}
protected void decrypt(String ipfile, String opfile) throws IOException
{
StringBuffer contents = new StringBuffer();
StringBuffer newContents = new StringBuffer();
BufferedReader input = null;
Writer output = null;
char letter, newLetter;
int uni, answer;
try
{
input = new BufferedReader(new FileReader(ipfile) );
String line = null;
output = new BufferedWriter( new FileWriter(opfile) );
while ((line = input.readLine()) != null)
{
contents.append(line);
for (int i = 0; i < contents.length(); i++)
{
letter = contents.charAt(i);
uni = (int)letter;
if (uni == 32)
{
answer = 32;
}
else if (uni == 13)
{
answer = 13;
}
else
{
answer = (((uni - 65) - 3)%26) + 65;
}
newLetter = (char)answer;
newContents.append(newLetter);
}
newContents.append(System.getProperty("line.separator"));
contents.delete(0, contents.length());
}
String newContentString = newContents.toString();
output.write(newContentString);
}
catch (IOException e)
{
System.out.println("I/O Error: " + e.getMessage());
System.exit(1);
}
finally
{
if (output != null) output.close();
}
}
Can anyone spot my mistake?
<Added>
EDIT:
Never mind. I figured it out. ^^;;
|
|
|
|
|
|
|
|