Ошибка объявления переменной — повторяющаяся локальная переменная
Люди, я новичок в java и начал только несколько недель назад. Я пытаюсь создать программу игры на угадывание, в которой вам нужно угадать число от 1 до 100, и возникает проблема.
Но тогда это дает мне сообщение об ошибке:
2 ответа
Ошибка довольно очевидна, это означает, что вы дважды объявляете переменную inputLine.
После того, как переменная объявлена с помощью String variableName , вы не можете сделать это снова, вам просто нужно ссылаться на созданную переменную с помощью variableName , чтобы вы перезаписали ссылку в памяти на новое значение.
На самом деле делает три вещи. Это
- создает (или «объявляет») переменную с именем inputLine ,
- читает строку из Scanner под названием input ,
- присваивает прочитанную строку переменной inputLine .
Это здорово в первый раз. Но позже, если вы повторите эту строку, вы фактически пытаетесь создать новую переменную с тем же именем, что и существующая.
Вместо того, чтобы повторять строку
Позже просто напишите
Который прочитает строку из Scanner и присвоит ее inputLine , не пытаясь создать новую переменную.
IntelliJ IDEA underlines variables when using += in JAVA
If you know what is the side effect in programming then it will be easy for you. To protect your variable from the side effect, the IDE shows the underline as a warning to you.
Hope this screenshot would help.

It’s a new feature of IntelliJ IDEA 2018.2:
Underlining reassigned local variables and reassigned parameters
IntelliJ IDEA now underlines reassigned local variables and reassigned parameters, by default. The attributes for all the languages supporting this feature, which for now include Java and Groovy, can be changed in Preferences/Settings | Editor | Color Scheme | Language Defaults | Identifiers | Reassigned.

Why it may be useful?
If the variable/parameter is underlined, you know that you can’t use it in lambda/anonymous class directly.
When reading a very long method code, if the parameter is not underlined, you know for sure that its value is not reassigned anywhere in this method and it contains exactly the same value that was passed to this method at any point.
Some code guidelines are against reassigned variables and you may want to avoid them where possible to keep the code clean and make it easier to read/debug.
Nowadays many developers prefer to avoid mutable state, and reassign variables only in rare cases when it is really necessary. We don’t want to manually enforce immutability, we suppose that everything is immutable by default and want to bring additional attention to the cases when something is not. If you use final to mark non-mutable variables it means that you need to write more code for regular cases and less code in exceptional cases. (BTW in modern languages declaring immutable variables doesn’t require writing additional code, but unfortunately not in Java).
Brian Goetz, Java Language Architect, also likes the way IntelliJ IDEA highlights reassigned variables (see his tweet).
Local Variables and Scoping Rules
One of the most fundamental knowledge in programming is understanding how to assess variables in the code. This concept is a cornerstone to the act of ‘coding with intention’ and mastering any programming language.
At the beginning of our journey, we are mostly focused on playing with code, exploring its limits and if it happens to achieve the needed task, then it is ‘good enough’.
Written by Mayumi Nishimoto
Software Engineer in tireless pursuit of improving my craft and in a journey to learn by sharing with the community.
Why are method parameters reassigned to local variables?
When viewing Java API source code, I often see method parameters reassigned to local variables. Why is this ever done?
This is in java.util.HashMap
This is a thread safety / performance improvement rule. values in HashMap is volatile. If you assign a variable to a local variable, it becomes the local variable of the stack, which is automatically thread safe. And much more, changing the local variable of the stack does not make it happen earlier, therefore, when using it, there is no penalty for synchronization (as opposed to mutability, when each record / record will cost you when you acquire / release the lock)
I need to look at some real examples, but the only reason I can do this is to keep the original value for some calculations at the end of the method. In this case, declaring one of the «variables» final will make this clear.