I have to admit that this was my fault and I recognized when Mr. Perfect asked me for help for this code.
I told you that you should always close your streams, right? There is an exception from that. Once you close System.in (or .err or .out), you can't just reopen it again. System.in is the input stream for your terminal. When you pack it into the Scanner and close the Scanner, the System.in is closed too.
I really didn't know that, because I usually get input via command line arguments or a GUI.
So I am sorry, that I gave a wrong advice in this case.
But what remains is: Always close your streams, unless it is a System. stream.
___________________________________________________________________
private static String Encrypt(String input, int places) {
char[] charArray = input.toCharArray();
for (char a : charArray) {
a += places;
if (places < 0) {
a = (char) (126 - places);
System.out.print(a);
} else if (a > 126) {
a = (char) (a % 126);
a += 32;
System.out.print(a);
} else {
System.out.print(a);
}
}
System.out.println();
return "";
}
Well done so far. I had to smile about your solution. You are kind of cheating here, Mr. Perfect.
The reason we structure the code into methods is reusability. Now imagine we want to create a graphical userinterface for that. We will just re-use the encrypt-method to get a result. That is not possible with your method, since it only prints out the correct result, but returns an empty string (the GUI will get and show that empty string).
Like I told you before: Don't use a foreach loop to modify your array. Rather do it like this:
for(int index = 0; index < charArray.length; index++) {
charArray[index] = //new value here, however this is how you can modify the array
//...
}
You just have to convert your charArray back to string when you are done and return that.
Your code doesn't comply with the Java code conventions. Here is a link to them:
http://www.oracle.com/technetwork/java/codeconv-138413.htmlIn your case it is the names of your methods. They have to start with a lowercase letter.
Last: You have an off-by-one-error:
If you enter the last character '~' and shift it by 1 it should return the first character ' ' (space). But you get the character right after the space.
An underflow doesn't seem to work at all. (i.e. type in space and a negative shift)