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.

  1. i copied code editor , performed fine using either version, tmp field or without. must have made other error using other method.

  2. java doesn't support pretty .tostring() arrays; object not override tostring 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 between arrays.tostring() , string.valueof(array). in case, want use string.valueof method.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -