Removing Characters within a string-Java -
i keep getting error removing character within string. have tried find on site , nothing has worked. not post. rather maybe answer explains why shows , how fix in case else encounters issue. without further due, here code:
public jtextfield clean() { string cleaner = topfield.gettext(); cleaner=cleaner.tolowercase(); int length = cleaner.length(); stringbuilder combiner = new stringbuilder(cleaner); (int x=0;x+1<length;x++) { char c = cleaner.charat(x); char c1 = cleaner.charat(x+1); if(c==' ' && c1==' ') { combiner.deletecharat(x); cleaner=combiner.tostring(); } if(c!='a' && c=='b' && c!='c' && c!='d' && c!='f' && c!='g' && c!='h' && c!='i' && c!='j' && c!='k' && c!='l' && c!='m' && c!='n' && c!='o' && c!='p' && c!='q' && c!='r' && c!='s' && c!='t' && c!='u' && c!='v' && c!='w' && c!='x' && c!='y' && c!='z' && c!=' ') {combiner.deletecharat(x); cleaner=combiner.tostring();} } topfield.settext(cleaner); return topfield; } i receive error states value out of bounds length of string input. please note method inside class created removes character not alphabet or space.
thanks in advance
there number of things pop out @ me.
- your basing loop on fixed value (
length), actual length ofstringcan decrease... - you potentially removing 2 characters per loop (there 2
deletecharatcalls) - the loop doesn't take account shrinking size of
string. example.x == 1, remove character @x, incrementx1 (x == 2), skipping character (the character @ position 2 @ position 1 - your
ifstatement unnecessarily long. in fact, depending on needs, usecharacter.isdigitorcharacter.isletter,character.iswhitespace
string cleaner = topfield.gettext(); cleaner = cleaner.tolowercase(); stringbuilder combiner = new stringbuilder(cleaner); int x =0; while (x < combiner.length()) { char c = combiner.charat(x); if (c >= 'a' && c <= 'z' || c == ' ') { combiner.deletecharat(x); } else { x++; } } from looks of code, appear wanting filter jtextfield allow numeric values. better use jspinner, jformattedtextfield or documentfilter , ensure correctness of data it's entered...imho
Comments
Post a Comment