So basically, I have to write a program that prompt 4 digit number in one dialog box to encrypt the numbers. encryptions are following.
Add 7 to each digit and then %10, swap 1st and 3rd digit, swap 2nd and 4th digit. display it in console box. Application should use loops to implement the algorithm
So here is my encrypt code.
import javax.swing.JOptionPane; public class Encryption { public static void main(String[] args) { String inputString; int num, digit1, digit2, digit3, digit4, encrypt; do { inputString = JOptionPane.showInputDialog("Please enter 4 digit numbers"); num = Integer.parseInt(inputString); } while(num/1000 == 0 || num/10000 != 0); digit1 = num/1000; digit2 = num/100; digit3 = num/10; digit4 = num/1; digit1 = (digit1+7)%10; digit2 = (digit2+7)%10; digit3 = (digit3+7)%10; digit4 = (digit4+7)%10; encrypt = digit1; digit1 = digit3; digit3 = encrypt; encrypt = digit2; digit2 = digit4; digit4 = encrypt; System.out.println("Your encrypted codes are: " + digit1 + digit2 + digit3 + digit4); } }
so far it seems to be working but is there another way(perhaps simpler way) to do it? Did i make any mistake?
Now.. here are my decryption code but this one seems to have problem. It works as long as first digit i put isn't 0.
What did I do wrong here? Again, I need to know way to fix it and if there's better way to do it, let me know. Thanks.
import javax.swing.JOptionPane; public class Decryption { public static void main(String[] args) { String inputString; int num, digit1, digit2, digit3, digit4, decrypt; do { inputString = JOptionPane.showInputDialog("Please enter 4 digit numbers"); num = Integer.parseInt(inputString); } while(num/1000 == 0 || num/10000 != 0); digit1 = num/1000; digit2 = num/100%10; digit3 = num/10%10; digit4 = num%10; if(digit1 <= 6 && digit1 >= 0) digit1 = digit1 + 10; if(digit2 <= 6 && digit2 >= 0) digit2 = digit2 + 10; if(digit3 <= 6 && digit3 >= 0) digit3 = digit3 + 10; if(digit4 <= 6 && digit4 >= 0) digit4 = digit4 + 10; digit1 = digit1 - 7; digit2 = digit2 - 7; digit3 = digit3 - 7; digit4 = digit4 - 7; decrypt = digit1; digit1 = digit3; digit3 = decrypt; decrypt = digit2; digit2 = digit4; digit4 = decrypt; System.out.println("Your encrypted codes are: " + digit1 + digit2 + digit3 + digit4); } }