I'm new at Java, I study on strings and i want a string to be reversed. Here is my code
String myStr = "abcdef"; String reversed = "";
for(int j=myStr.length()-1;j>=0;j--) {
myStr.charAt(j) += reversed;
}
But it gives me an error message:
****.java:14: error: unexpected type
required: variable
found: value
But when I print it by System.out.print(reversed)
, it prints reversed
correctly. What is the difference between variable and value? Why it can give me correct answer in spite of giving me an error message? I'll appreciate your answers, thanks
The problem is here:
myStr.charAt(j) += reversed;
The left-hand-side is a value. Not a variable. That's why you can't to a +=
to it.
Although it defeats the purpose of learning how do it the hard way, you can do it like this:
myStr = new StringBuffer(myStr).reverse().toString();
it sould be reversed += new String(myStr.charAt(j));
... the unexpected type is that what charAt(j) returns
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With