Reputation: 93
For my Computer Science class, I had to create a Caesar Cypher that takes in two or three command line arguments, the first is a key which is the amount each letter in the message will be shifted, the second is the file which contains the original message, and the third is optional and if present it creates the specified file with the encrypted code, and if absent the output is printed to the screen. Everything works fine except that it removes the spaces, for example if I pass in a key of 5 and the message "Hello, my name is Dave.", it prints "Mjqqt1r~sfrjnxIf{j3" and if I pass in -5 and "Mjqqt1r~sfrjnxIf{j3", it prints "Hello,mynameisDave." How can I make it not remove the spaces?
import java.io.*;
import java.util.*;
public class Caesar
{
public static void main(String[] args)
{
int key = Integer.parseInt(args[0]);
Scanner in = null;
PrintWriter out = null;
try
{
in = new Scanner(new File(args[1]));
if(args.length == 3)
{
out = new PrintWriter(args[2]);
}
while(in.hasNextLine())
{
char[] charVal = in.next().toCharArray();
for(int i = 0; i < charVal.length; i++)
{
if(charVal[i] < 32 || charVal[i] > 126)
{
charVal[i] = charVal[i];
}
else
{
charVal[i] = (char) (charVal[i] + key);
}
if(charVal[i] > 126)
{
charVal[i] = (char) (charVal[i] - 95);
}
else if(charVal[i] < 32)
{
charVal[i] = (char) (charVal[i] + 95);
}
}
if(out != null)
{
out.print(charVal);
}
else
{
System.out.print(charVal);
}
}
}
catch (FileNotFoundException e)
{
System.out.println("Error: File not found.");
e.printStackTrace();
}
finally
{
in.close();
if(out != null)
{
out.close();
}
}
}
}
Upvotes: 1
Views: 144
Reputation: 1007
Have you tried debugging your code ?
That would be a good way to figure out what conditional branch is executed what a space character is encountered.
But by examining your code I can say that the problem is in your first if-else block here:
if(charVal[i] < 32 || charVal[i] > 126)
{
charVal[i] = charVal[i];
}
else
{
charVal[i] = (char) (charVal[i] + key);
}
Remember that the integer ASCII value of space is 32. So, the else block gets executed even for a space.
You'd need to change your if-condition to make sure that the if block handles the space as well.
EDIT:
Also, in.Next() get's the next "word". That's why the space will never be in charVal array.
Upvotes: 0
Reputation: 719307
Hints:
Lookup the character value for the space character; e.g. man ascii
or Google it.
Examine your code carefully to see what happens to a space in the input string ... and why. Then figure out what to do to avoid it.
Use the debugger Luke ...
Upvotes: 0
Reputation: 176753
Try using in.nextLine()
instead of in.next()
. in.next()
basically looks for the next word, and gives you them one at a time. That's why the spaces are disappearing.
Upvotes: 2