-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExercise12.java
More file actions
72 lines (68 loc) · 2.64 KB
/
Exercise12.java
File metadata and controls
72 lines (68 loc) · 2.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
public class Exercise12 {
public static void main(String[] args) {
//print out the word and check.
System.out.print("'Captain Crunch' as encoded is: ");
// run method and write result
String myResult = encode("Captain Crunch", 21);
System.out.println(myResult);
//print out the word and check.
System.out.print("'"+myResult+"'" +" as decoded is: ");
// run method and write result
System.out.println(encode(myResult, -21));
}
public static String encode(String s, int n) {
String newString = "";
//if (n==26||n==-26)n=0; doesn't work if greater than 26
//remainder if divided by 26
//works well if number is greater than 26
n=n%25;
int charz = 'z';
int chara = 'a';
int charZ = 'Z';
int charA = 'A';
char curChar = ' ';
int loc;
String alphaChar = "abcdefghijklmnopqrstuvwxyz";
String alphaUChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for(int i = 0;i < s.length();i++) {
curChar = s.charAt(i);
if (chara <= curChar && curChar <= charz ) {
loc = -1;
loc = alphaChar.indexOf(curChar);
// curChar is lower case and within a to z
// changes character to an integer value
if (loc >= 0 && loc <= 25){
loc = loc + n;
if (loc > 25){
loc = loc - 26;
}
else if (loc < 0){
loc = 26 + loc;
}
newString = newString + alphaChar.charAt(loc);
}
} else if (charA <= curChar && curChar <= charZ ) {
//Same type of work, but for capital letters
loc = -1;
loc = alphaUChar.indexOf(curChar);
// curChar is lower case and within a to z
// changes character to an integer value
if (loc >= 0 && loc <= 25){
loc = loc + n;
if (loc > 25){
loc = loc - 26;
}
else if (loc < 0){
loc = 26 + loc;
}
newString = newString + alphaUChar.charAt(loc);
}
} else {
// handles spaces and characters that aren't letters
newString = newString + (char)curChar;
}
// index to next character in the string
}
return newString;
}
}