开发者

How do I use a variable defined in an 'if' statement?

public class Help
{
    public static void main (String[] args)
    {
        if (index = 1)
        {
            String greeting = "hello";
        }
        else
        {
            String greeting = "goodbye";
        }
    }

    call开发者_StackOverflow中文版AMethod(greeting);
}

When I define the String within the if statement I get a 'cannot find symbol' error. How can I get around this and still be able to create a string depending upon an above condition?


How about

public static void main (String[] args){
    String greeting;
    if( index == 1){
       greeting = "hello";
    }else{
       greeting = "goodbye";
    }
 }

 callAMethod(greeting);
}


Declare it outside the scope -

String greeting = "goodbye";
if( index == 1)
{
    greeting = "hello";
}

callAMethod(greeting);


Declare the variable outside of the if block.

Right before the if statement, you can say String greeting = "";

Then, inside the if and else blocks, you say greeting = "hello"; and so on.

So you have separated declaring the variable from assigning the value to it.


You can define the greeting variable before the statement:

String greeting;

if (index == 1) {
   greeting = "hello";
} else {
   greeting = "bye";
}

System.out.println(greeting);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜