Day 2

June 4th (Tuesday)

Objectives:

  • String class
  • Decision structures (if-else, switch)
  • Iteration structures (for-loops and while-loops, break and continue)

Lab assignment:

Bonus: (Cryptography)

A small store wants to send data over the Internet, so they asked you to write a program that will encrypt it so that it may be transmitted more securely.

All the data will be transmitted as four-digit integers. Your application should read a four-digit integer entered by the user and encrypt it as follows:

  • replace each digit with the result of adding 3 to the digit and getting the remainder after dividing the new value by 10, then
  • swap the first digit with the third, and swap the second digit with the fourth, then
  • print the encrypted integer.

Write a separate application that inputs an encrypted four-digit integer and decrypts it (by reversing the encryption scheme) to form the original number.


Example: let's encrypt number 4859

4 --> (4+3) mod 10 = 7

8 --> (8+3) mod 10 = 1

5 --> (5+3) mod 10 = 8

9 --> (9+3) mod 10 = 2

It gives us 7 1 8 2, then we do the swap and get 8271.

So 4859 is encrypted as 8271.


To decrypt: let's decrypt 8271

First, we will swap appropriate digits in 8271 and get 7182, then we will "undo" addition of 3 with remainder

7 --> (7-3) mod 10 = 4

1 --> (1-3) mod 10 = (-2) mod 10 = 8

Be careful! check that % does works correctly on negative numbers

8 --> (8-3) mod 10 = 5

2 --> (2-3) mod 10 = (-1) mod 10 = 9

Which gives us 4859.

So 8271 is decrypted into 4859.

here you can find Java API documentation:

http://docs.oracle.com/javase/8/docs/api/index.html