Note that there are some explanatory texts on larger screens.

plurals
  1. POjava basic encryption program
    text
    copied!<p>I'm trying to make a basic encryption program that used random numbers to encrypt the whole alphabet, encrypt a user submitted phrase and then decrypt it back to the original phrase but I am finding it very hard. Can anyone help point out my mistakes please! It shouldn't code two letters to the same letter, ie a and b shouldn't ever be both matched to c.</p> <pre><code>public class MainClass { public static final int ALPHASIZE = 26; public static final char[] Lalpha = { 'a','b','c','d','e','f','g','h','i','j','k','l', 'm','n','o','p','q','r','s','t','u','v','w','x','y','z' }; public static final char[] Ualpha = {'A','B','C','D','E','F','G','H','I','J','K','L', 'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z', }; protected static char[] encryptU = new char[ALPHASIZE]; protected static int[] decrypt = new int[ALPHASIZE]; protected static char[] encryptL = new char[ALPHASIZE]; Random rgenerator = new Random(); public MainClass(){ int randNum = rgenerator.nextInt(ALPHASIZE); for(int i=0; i&lt;ALPHASIZE ; i++) { //makes sure that it won't assign a letter to itself or to one that has already been assigned do { randNum = rgenerator.nextInt(26); } while (randNum%26==0 &amp;&amp;Arrays.asList(encryptU).contains(Ualpha[randNum])); encryptU[i] = Ualpha[randNum]; encryptL[i] = Lalpha[randNum]; decrypt[i] = randNum; } } public String encrypt(String secret) { System.out.println(Arrays.toString(encryptU)); int position = 0; char[] mess = secret.toCharArray(); for(int i = 0 ; i&lt;mess.length;i++) { if(Character.isUpperCase(mess[i])) { for(int j = 0; j &lt; encryptU.length; j++) { if(mess[i]==Ualpha[j]) { position = j; } mess[i] = encryptU[position]; } } if(Character.isLowerCase(mess[i])) { for(int j = 0; j &lt; encryptU.length; j++) { if(mess[i]==Lalpha[j]) { position = j; } mess[i] = encryptL[position]; } } } return new String(mess); } public String decrypt(String secret) { char[] mess = secret.toCharArray(); for(int i = 0 ; i&lt;mess.length;i++) { if(Character.isUpperCase(mess[i])) { for(int j = 0; j&lt;ALPHASIZE; j++){ if(mess[i]==encryptU[j]){ mess[i] = Ualpha[j]; } } } if(Character.isLowerCase(mess[i])) { for(int j = 0; j&lt;ALPHASIZE; j++){ if(mess[i]==encryptL[j]){ mess[i] = Lalpha[j]; } } } } return new String(mess); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload