Using variables outside of an if-statement

后端 未结 2 2048
甜味超标
甜味超标 2020-12-04 00:08

I\'m not entirely sure if this is possible in Java, but how would I use a string declared in an if-statement outside of the if-statement it was declared in?

2条回答
  •  我在风中等你
    2020-12-04 00:44

    You need to distinguish between a variable declaration and assignment.

    String foo;                     // declaration of the variable "foo"
    foo = "something";              // variable assignment
    
    String bar = "something else";  // declaration + assignment on the same line
    

    If you try to use a declared variable without assigned value, like :

    String foo;
    
    if ("something".equals(foo)) {...}
    

    you will get a compilation error as the variable is not assigned anything, as it is only declared.

    In your case, you declare the variable inside a conditional block

    if (someCondition) {
       String foo;
       foo = "foo";
    }
    
    if (foo.equals("something")) { ... }
    

    so it is only "visible" inside that block. You need to move that declaration outside and assign it a value somehow, or else you will get conditional assignment compilation error. One example would be to use an else block :

    String foo;
    
    if (someCondition) { 
       foo = "foo";
    } else {
       foo = null;
    }
    

    or assign a default value (null?) on declaration

    String foo = null;
    
    if (someCondition) {
       foo = "foo";
    }
    

提交回复
热议问题