Problem with the scope of [JAVA] variables

Source: Internet
Author: User
Tags variables readline return variable tostring variable scope
Variable | problem
Problem with variable scope: public string Getanswer () {string myanswer;      try {BufferedReader bfreader=new BufferedReader (New InputStreamReader (system.in));   Myanswer=new String (Bfreader.readline (). toString ());      System.out.println ("You enter is:" +myanswer);   catch (Exception e) {} return myanswer; } }

This method is always an error, according to the previous thinking, Myanawer should have been assigned, how can it be not yet assigned value?

It turns out that this is the scope of the variable, and I'll change it to:

public string Getanswer () {string Myanswer=new string (""); Note Here/* Summary: A variable defined within an area must be new in this area, like this method, you cannot use String myanswer, and then the next layer of parentheses new*/try {bufferedreader bfreader=new Buf   Feredreader (New InputStreamReader (system.in));   Myanswer=bfreader.readline (). toString ();      System.out.println ("You enter is:" +myanswer);   catch (Exception e) {}//system.out.println (myanswer); return myanswer; }

Because the scope of the variable cannot jump out of the pair of braces that it allocates space for.

Of course, you can also use string myanswer to jump out of the body of the method directly as a variable in the class, and you can also work with this variable 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 is:" +myanswer);     catch (Exception e) {} return myanswer; }


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.