[Java] problem of variable scope

xiaoxiao2021-03-06  16

Variable scope problems: public String getAnswer () {String myAnswer; try {BufferedReader bfReader = new BufferedReader (new InputStreamReader (System.in)); myAnswer = new String (bfReader.readLine () toString ().); System. Out.println ("You entered:" myanswer);} Catch (Exception E) {} return myanswer;}}

This method always reports wrong. According to the previous ideas, MyanaWer should have assigned, how can I not assign a value?

It turns out that this is the problem of variables, I change it to:

Public string getanswer () {string myanswer = new string (""); // Note Here / * Summary: Defined variables in a certain area, must be new, like this method in this area, you can't use String Myanswer; Then then next groups of new * / try {bufferedreader bfreader = new bufferedreader (NEW INPUTSTREAMREADER (ISTEMREADER ()); myanswer = bfreader.readLine (). Tostring (); //system.out.println ("You Enter The " myanswer);} catch (exception e) {} //system.out.println (myanswer); return myanswer;}

Because the scope of the variable cannot jump out of the pair of braces it allocate space.

Of course, the String Myanswer can be jumped out of the method, directly as a variable in the class, then this variable can also be used directly in the method. Such as

String myAnswer; public String getAnswer2 () {try {BufferedReader bfReader = new BufferedReader (new InputStreamReader (System.in)); myAnswer = new String (bfReader.readLine () toString ().); System.out.println ( "You Enter: " myanswer);} catCH (Exception E) {} return myanswer;}

转载请注明原文地址:https://www.9cbs.com/read-41869.html

New Post(0)