java - Using charAt() to change a char array -
i'm utterly boggled why charat()
works in scenarios not others. doing exercises while learning java , 1 of them take string, , return in reverse order.
my working code:
public string reversestring(string tempstr){ int initialindex = tempstr.length()-1; int reverseindex = 0; char tmp; char[] array = new char[tempstr.length()]; for(int tempchar : array){ tmp = tempstr.charat(initialindex); array[reverseindex] = tmp; initialindex--; reverseindex++; } string returnstr = new string(array); return returnstr; }
the problem ran using following for
statement prints gibberish:
for(int tempchar : array){ array[reverseindex] = tempstr.charat(initialindex); initialindex--; reverseindex++; }
there perhaps dozen different variants of using while
loops, standard for
loops , few other versions of code ugly , didn't work. why did making char tmp
field, putting inspected characrer in said field, , using said field enter data array work?
also, why unable return string using return array.tostring();
?
edit: i'm using latest eclipse downloaded today, switched netbeans.
i copied code editor , performed fine using either version,
tmp
field or without. must have made other error using other method.java doesn't support pretty
.tostring()
arrays; object not overridetostring
produce hashcode of object rather contents/fields of object, , arrays no exception here. whilst might seem sensible character arrays, same operation on int array produce nonsense; see difference betweenarrays.tostring()
,string.valueof(array)
. in case, want usestring.valueof
method.
Comments
Post a Comment