Error: Unexpected type required

Asked

Viewed 257 times

-1

This code should invert a string given by the first argument, but has a build 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 build error is as follows:

Ex4.java:27: error: Unexpected type required: variable found: value Ex4.java:28: error: Unexpected type required: variable found: value

1 answer

-1

You cannot 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 it:

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();
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.