Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unexpected type error

Tags:

java

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

like image 911
El3ctr0n1c4 Avatar asked Jan 04 '12 22:01

El3ctr0n1c4


2 Answers

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();
like image 129
Mysticial Avatar answered Sep 27 '22 20:09

Mysticial


it sould be reversed += new String(myStr.charAt(j)); ... the unexpected type is that what charAt(j) returns

like image 31
A4L Avatar answered Sep 27 '22 19:09

A4L