Pregunta

Why does this work:

char c = 5;
int i = c++;

But this throws a compiler error (Invalid Argument to Operator ++/--):

int i = argv[0].charAt(0)++;
¿Fue útil?

Solución

The ++ operator works on variables and expressions returning references to something writable, not on all values in general. In other words, there is simply no way to write the value of an incremented char back into the original string, so charAt(0)++ is an error.

You can work around this problem by converting argv[0] to an array of characters, and incrementing a value inside that array.

Otros consejos

The increment operator can only be applied to lvalues, which means expressions which evaluate to something that can appear on the left side of an assignment expression. Return value of a function is not an lvalue.

There is no connection between your charAt(0) call and the location in the underlying char[] wherefrom this char value was read. If you had

argv[0].value[0]++;

that would work, but value is

private final char[] value;

in the immutable String class.

Simply put: it needs a variable. This is not a
variable argv[0].charAt(0) but a method call.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top