Java Unscrabling character string even length works but odd length doesnt -
i'm writing program has multiple encoding schemes , 1 of them prime shift, based on whither key or odd. decoding scheme follows ::
the key checked see whether odd or even. odd key, odd numbered characters in order first in new string, indexes. if key even indexes first, odd indexes
so string "abcdefg" , key of 27 new string should "bdfaceg" if key 28 new string should "acegbdf"
oddly enough if key odd, , string length odd or even, decodes perfectly. if key , string length decode fine,
but if key , string length odd not decode right.
using test string "enter message here." these out puts::
encoded key = 28 ; encoded message "etrmsaehr.ne esg ee" message length = 19 decoded key = 28 ; decoded message "e.tnrem seasegh renull" so entries in right place, odd ones either need pulled inversely or pushed on odd index, think... think pushing them index easiest, i'm still new java , don't know how that.
here code function using @ instance.
protected string decode(string a, int k) { system.out.println(a.length()); string[] out = new string [a.length()]; string decode = a; int key = k; boolean kp = iseven(key); string odd = ""; if (kp) { //key try { int f = 0; (int =0 ; i<(a.length()/2); i++) { out[f] = character.tostring(a.charat(i)); f+=2; } int g = 1; (int = (a.length()/2) ; i<(a.length()); i++) { out[g] = character.tostring(a.charat(i)); g+=2; } } catch ( indexoutofboundsexception e ) { system.out.println("out of bounds"); while(true) break; } } else { //key odd try { int f = 1; (int =0 ; i<(a.length()/2); i++) { out[f] = character.tostring(a.charat(i)); f+=2; } int g = 0; (int = (a.length()/2) ; i<(a.length()); i++) { out[g] = character.tostring(a.charat(i)); g+=2; } } catch ( indexoutofboundsexception e ) { system.out.println("out of bounds"); while(true) break; } } (int = 0 ; i<a.length(); i++) odd += out[i]; system.out.println(odd); return(odd); }
your problem when it's key , odd string, there 1 more character in first "sequence" of encoded string, , don't account this:
if key 28 new string should "acegbdf"
above example has 4 characters first, 3 characters last.
in code you're running (a.length()/2) in above string 3, , means work index 0, 1, , 2. when wanted work 0, 1, 2, , 3 ("aceg").
the solution add 1 condition in both loops key... this solve outofboundsexception failed tell about!
just cautionary note: believe "solution" cause length strings fail, it's not job homework. :)
Comments
Post a Comment