Unexpected error

I am new to Java, I am learning strings and want the string to be undone. Here is my code

String myStr = "abcdef"; String reversed = ""; for(int j=myStr.length()-1;j>=0;j--) { myStr.charAt(j) += reversed; } 

But this gives me an error message:

 ****.java:14: error: unexpected type required: variable found: value 

But when I print it System.out.print(reversed) , it prints reversed correctly. What is the difference between a variable and a value? Why can he give me the correct answer, despite the fact that he gave me an error message? I will be grateful for your answers, thank you

+4
source share
6 answers

The problem is here:

 myStr.charAt(j) += reversed; 

The left side is the meaning. Not a variable. That is why you cannot use += for this.


Although it is detrimental to the purpose of learning how to do this, you can do it as follows:

 myStr = new StringBuffer(myStr).reverse().toString(); 
+4
source

it can be reversed += new String(myStr.charAt(j)); ... an unexpected type is that charAt (j) returns

+2
source
 String myStr = "abcdef"; String reversed = ""; for(int j = myStr.length()-1 ; j >= 0; j--) { reversed += myStr.CharAt(j); } 
+1
source

+= works with a variable, not a value. myStr.charAt(j) returns a value, and you cannot use += for this value. It must be a variable of type reversed . eg.

 reversed += myStr.substring(j, j+1); 
0
source

You want reversed += myStr.charAt(j) . You can assign a value to a variable. myStr.charAt(j) not a variable. This is an expression that returns a value or type char.

You should also use StringBuilder and add each char to StringBuilder, because your loop creates a new instance of String at each iteration, which is inefficient at all.

0
source

Variables are places where you can store values. They must be declared and assigned a value before use:

 String reversed = ""; 

reversed is the variable assigned to the value "" . Only variables can be on the left side of the task (for example, = ). += - special type of destination. a += b; basically coincides with a = a + b; .

Values ​​are the results of expressions. Expressions are things like variable references ( reversed ), constants ( "" ), method calls ( myStr.charAt(0) ), and operations ( a + b ). Values ​​can be on the right side of the task.

I am not sure why it gives you the correct answer, since the code should not run at all when you have a compilation error.

0
source

Source: https://habr.com/ru/post/1389365/


All Articles