-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencoder.java
More file actions
51 lines (47 loc) · 1.57 KB
/
Copy pathencoder.java
File metadata and controls
51 lines (47 loc) · 1.57 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
import greenfoot.*;
import java.util.Scanner;
public class encoder extends Actor
{
private String encoded = "";
public void act()
{
}
public void coder(String text, int method) {
encoded = "";
if(method == 1) {
for(int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
encoded += decodeCharacter(c, ((MyWorld) getWorld()).offset);
}
System.out.println(encoded);
} else if(method == 0) {
for(int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
encoded += encodeCharacter(c, ((MyWorld) getWorld()).offset);
}
System.out.println(encoded);
}
}
private char encodeCharacter(char c, int offset) {
if (Character.isLetter(c)) {
int start = Character.isLowerCase(c) ? 'a' : 'A';
return (char)(((c - start + offset) % 26) + start);
} else if (Character.isDigit(c)) {
return (char)(((c - '0' + offset) % 10) + '0');
} else {
return c;
}
}
private char decodeCharacter(char c, int offset) {
if (Character.isLetter(c)) {
int start = Character.isLowerCase(c) ? 'a' : 'A';
int decoded = ((c - start - offset + 26) % 26) + start;
return (char) decoded;
} else if (Character.isDigit(c)) {
int decoded = ((c - '0' - offset + 10) % 10) + '0';
return (char) decoded;
} else {
return c;
}
}
}