Error: unexpected type required

-1

This code should invert a string given by the first argument, but has a compilation error

public class ex4 {

    public static void main (String args[]) throws IOException {
        int strlength=length(args);
        InvertString(args, strlength, 0);
    }

    public static int length(String args[]) {
        int i=0;
        int count=0;
        while(Character.isLetter(args[0].charAt(i))) {
           count++;
           i++;
        }

        return count;
    }

    public static void InvertString(String args[], int i, int x){
        char a= args[0].charAt(x);
        args[0].charAt(x)=args[0].charAt(i-1-x);
        args[0].charAt(i-1-x)=a;
        x++;

        if(x<(i/2)) InvertString(args,i,x);
    }
}

The compilation error is as follows:

  

ex4.java:27: error: unexpected type required: variable found: value   ex4.java:28: error: unexpected type required: variable found: value

    
asked by anonymous 01.05.2016 / 03:37

1 answer

-1

You can not use this because string in Java is immutable.

args[0].charAt(x)=args[0].charAt(i-1-x);
args[0].charAt(i-1-x)=a;

Do this:

StringBuilder myName = new StringBuilder(args[0]);
myName.setCharAt(x,args[0].charAt(i-1-x));
myName.setCharAt(i-1-x,a);
x++;

if(x<(i/2)) InvertString(myname,i,x);
}

To invert the string you can use this code below:

public class InvertString
{
  public static void main(String[] args)
  {
    String resultado = invertString(args[0]);
    System.out.print(resultado);
  }

  public static String invertString(String stringToInvert){
    StringBuilder builder = new StringBuilder();
    for (int i=stringToInvert.length()-1; i >= 0; i--){
        builder.append(stringToInvert.charAt(i));
    }
    return builder.toString();
  }
}
    
01.05.2016 / 04:10