You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: projects/create-a-ceasar-cipher-with-java/create-a-caesar-cipher-with-java.mdx
+9-9Lines changed: 9 additions & 9 deletions
Original file line number
Diff line number
Diff line change
@@ -44,7 +44,7 @@ So, he pulled off a kinda genius move... he shifted each letter in his messages
44
44
45
45
This meant that "attack at dawn" would become "dwwdfn dw gdzq" to any nosey enemies.
46
46
47
-
```terminal
47
+
```
48
48
Wms fytc y jckmlybc kmsrf!
49
49
```
50
50
@@ -54,7 +54,7 @@ The text above contains an _encrypted_ message, and more specifically, a Caesar
54
54
55
55
For example, let's say we shift the letters by 3:
56
56
57
-
```terminal
57
+
```
58
58
A → D
59
59
B → E
60
60
C → F
@@ -117,7 +117,7 @@ for (int i = 0; i < chars.length; i++) {
117
117
118
118
We are using the `.toCharArray()` method to turn our user's text into a char array to loop through it. This is what you would have if the value of `text` was "hello":
This `if`/`else` shorthand (`?``:`) called the ternary operator provides either the `a` or `A` character depending if the letter is upper case or lower case.
145
145
146
-
```terminal
146
+
```
147
147
condition ? valueIfTrue : valueIfFalse
148
148
```
149
149
@@ -171,24 +171,24 @@ Let's say we are trying to shift `C` 3 spaces. Since 'C' is uppercase, the base
171
171
172
172
If we subtract the base from the character, we get:
173
173
174
-
```terminal
174
+
```
175
175
character - base = 'C' - 'A' = 67 - 65 = 2
176
176
```
177
177
So 'C' is the 2nd letter in the alphabet (index 2, starting from 0). Now we have the index of our letter, but since we're trying to shift it 3 spaces, let's add `3` to the current index.
178
178
179
-
```terminal
179
+
```
180
180
(character - base + shift)
181
181
```
182
182
183
183
Let's also make sure that it _wraps_ around the alphabet, so `Z` shifted 3 spaces makes it to `C`. We can use the `%` modulo.
184
184
185
-
```terminal
185
+
```
186
186
(character - base + shift) % 26
187
187
```
188
188
189
189
Since we have a new index now, we can add our base to turn it _back_ to an ASCII value to turn it into a new letter!
190
190
191
-
```terminal
191
+
```
192
192
(character - base + shift) % 26 + base
193
193
(67 - 65 + 3) % 26 + 3 = 70
194
194
```
@@ -242,7 +242,7 @@ You'll need two things from the user:
242
242
- text to encrypt (String)
243
243
- the shift number (0-25) (int)
244
244
245
-
```terminal
245
+
```
246
246
Enter text to encrypt: Thank you Penguin123 for keeping Club Penguin safe. Here are four hundred coins.
0 commit comments