0

I have this situation:

...
char aux = 'a';
String sent;
sent = scan.nextLine();
//now imagine the user types "hello"
for ( int n = 0 ; n <= sent.length() ; n++ )
{
 if ( (float) n % 2 == 0 )
        {
         //here, i need to put the value of the aux 
         //inside the nth position of the string Sent
        }
}

I'm very used to do this in C/C++, but I'm having some problems with java. I tried using the "sent.charAt(n)=aux;" method, but it does not seems to work, it just returns the error " unexpected type. required: variable. found: value."

Is there any easy way for me to swap those string values to the one stored in the "aux", or I really need to create another method?

James Douglas
  • 3,328
  • 2
  • 22
  • 43
CH4B
  • 37
  • 6

1 Answers1

0

There is no such way to change a String. String in Java is immutable. You could split the String by n and concatenate again with aux. Something like:

...
char aux = 'a';
String sent;
sent = scan.nextLine();
//now imagine the user types "hello"
for ( int n = 0 ; n <= sent.length() ; n++ )
{
  if ( (float) n % 2 == 0 )
  {
    sent = sent.substring(0, n) + aux + sent.substring(n);
  }
}
Jue
  • 1
  • 1