indexoutofboundsexception - Null Cipher -- Java -
i'm trying code null cipher school assignment, , have no idea i'm doing wrong.
the cipher supposed obtain char number given in pattern class. if it's "-1", end program , return output. if pattern returns "0", skip word , move on next pattern value. other integer , program should char word in place.
so in example below, pattern {1, 0, 0, 1, 5, -1} , text is: "hello, me you're looking for".
the output should : "hmr"
but i'm getting out of bounds error, , when tweak it, it's not printing correct chars.
the code below, please me.
edit: change runtimeerror disappear, i'm getting incorrect output: "e'[space]"
arraylist<character> text; arraylist<character> output; int outputlen; arraylist<integer> pattern; public preform() { text = new arraylist<character>(); output = new arraylist<character>(); pattern = new arraylist<integer>(); { pattern.add(1); pattern.add(0); pattern.add(0); pattern.add(1); pattern.add(5); pattern.add(-1); } } public void updatelength() { outputlen = output.size(); } public void stringtochar(string input) { (int = 0;i < input.length();i++) { string value = input.substring(i,i+1); text.add(value.charat(0)); } } public void printstring () { (int = 0; < output.size();i++) { system.out.println(output.get(i) + ", "); } } public arraylist<character> run() { int nullvalue = 0; int textval = 0; (int = 0; < pattern.size(); i++) { nullvalue = pattern.get(i); if (nullvalue == -1) { return output; } else if (nullvalue == 0) { textval = nextword(textval); } else { textval += nullvalue; char temp = text.get(textval); output.add(temp); textval = nextword(textval); } } return output; } public int nextword (int starting) { // go next word int addval = 0; do{ starting++; } while(text.get(starting).equals(' ')); addval += starting; return addval; } public static void main (string[] args) { preform event = new preform(); event.stringtochar("hello, me you're " + "looking for"); event.run(); event.printstring(); }
thank you!
for exception: in run have check pattern.size()
not test.size
. @ line exception.
a similar issue in run compare text size, mean pattern
apart code way complicated, i.e. instead of nextword can use "my string".split(" "); , array of string containing each word. there few other issues, that's figure out (its assignment after all)
edit: main logic issue way use nextword in run. first need adapt nextowrd want (skip until next space , start of next word):
public int nextword (int starting) { // go next word do{ starting++; } while(!text.get(starting).equals(' ')); // skip space starting++; return starting; }
and logic in run correct char needs adapted too:
else { char temp = text.get(textval + nullvalue - 1); output.add(temp); textval = nextword(textval); }
Comments
Post a Comment