Caesar Cipher java my way, doesnt work -



Caesar Cipher java my way, doesnt work -

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

so here idea. create 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 downwards 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 next 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 utilize 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 alter d message.charat(i) = d , after 3 iteration of for(int j =0; j < alphabet.length; j++) if statement true 1 time again , d in string replaced g , on. solution problem next 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));

java

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -