Link to home
Start Free TrialLog in
Avatar of Kody-Burg
Kody-BurgFlag for United States of America

asked on

Simple Java Shift Encryption

Hello everyone!

I am new to the world of java programming, and I am working on basic shift encrytion. Here is what I need the program to do:

User inputs a single lower-case letter or upper-case letter or number (0-9).

User inputs number of places to shift letter or number (i.e. user types in 0 and shifts 2, the encrypted output is 2).

I have the code working to shift the input successfully, but I can't get the numbers or letters to wrap around. I need to limit this to letters and numbers only, no special characters.

I am converting the input char to its ASCII value to do the operations.

Any suggestions on how to detect input and do the wrap around?

Example of what I mean by wrap around:

User inputs Z and shifts 2 places, should be come a B, not a \.

Thank you in advance!

Kody
Avatar of Kody-Burg
Kody-Burg
Flag of United States of America image

ASKER

I believe what I am trying to do is make a very simple single char input caesar shift, limited to only letters and numbers.
Sorry, I wanted some clarification - are you talking about
real ASCI representation or
you  say have sequence

"ABCDEFGHIJKLMNOPQRASTUVWXYZ"

and you want to shift within this sequence and wrap around  if necessary

Becuase if you do something with ASCII representations you'll of course need to go
out of this set,

So then do you shift numbers within numbers and leters within letters?

If this is so, I think you can implement wrap around using "%" operator (modulo n)

If this is about real ASCII representation then something else is required







 
ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
What I need to do is this:

If input is a number, stay within that range. EX: input is 0 so you can only shift in the range 0 - 9

if input is a capital letter, stay within that range EX: input is A so you can only shift in the range of A-Z

Does this make sense? So if I'm at a capital Z, and enter shift 2, it should become a capital B.

I was able to make it work by modifying the code that you provided for me. Thank you!
Well then the same idea as I showed above.

This is the static method which can do it



static  String [] MyStrings = {
"0123456789",
 "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyz",

}

input character is in String s:

public static string Encode(String s, int shift){


String snew = null;

for (int j=0; j<myStrings.length; j++){
if(myStrings[j].indexOf(s) == -1)continue;

snew = "" + myStrings[j].charAt((myStrings[j].indexOf(s) + shift)%myStrings[j].length());


}

if(snew == null){
System.out.println("It was not digit opr letter");
}
else
System.out.println(snew);


}
return snew;

}