Caesar Cipher java my way, doesnt work -


i know there bunch of topics caesar cipher solve things way. , such doesnt work ,but think might work way.i sure know feeling when alone solve problem.

so here idea. make array of chars consist alphabet. , string message code. 2 loops. 1 outer set char message, , inner scans thru alphabet array. when letter message meet char in array, replaces him 3rd (key of 3) char down in array.

here piece of code written now:

    char[] alphabet = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'o', 'p','r','s','t','u', 'v', 'z'};      string message = " message coding";      message = message.tolowercase();     string codedmsg = "";        for(int = 0; < message.length(); i++)     {          for(int j =0; j < alphabet.length; j++)         {             if(message.charat(i) == alphabet[j])             {     codedmsg += alphabet[j +3 ]; 

it complies well, receive following error when run :

exception in thread "main" java.lang.arrayindexoutofboundsexception: 23         @ sifra.main(sifra.java:19) 

you're problem have alphabet[j + 3]. because j < alphabet.length, when j = alphabet.length - 2 alphabet[j + 3] becomes alphabet[alphabet.length + 1] go outside array.

to solve can use alphabet[(j + 3)%alphabet.length].

now code run not correct.

because manipulate message replaced many times in inner loop.

for(int j =0; j < alphabet.length; j++)         {             if(message.charat(i) == alphabet[j])             {                 message = message.replace(message.charat(i), alphabet[j + 3]); // line problem 

if message.charat(i) = a true if(message.charat(i) == alphabet[j]) , a in sting change d message.charat(i) = d , after 3 iteration of for(int j =0; j < alphabet.length; j++) if statement true again , d in string replaced g , on. solution problem following there many more:

     char[] alphabet = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'o', 'p','r','s','t','u', 'v', 'z'};          string message = " message coding";          message = message.tolowercase();         char[] messagearray = message.tochararray();          for(int = 0; < message.length(); i++)         {             for(int j =0; j < alphabet.length; j++)             {                 if(message.charat(i) == alphabet[j]){                     messagearray[i] = alphabet[(j + 3)%alphabet.length];                 }             }         }         system.out.println(string.copyvalueof(messagearray)); 

Popular posts from this blog