JAVA: Is it possible to use a variable outside a loop that has been initialised inside a loop?

廉价感情. 提交于 2021-02-16 13:29:07

问题


I'm a new programmer trying to practice by making a game. I want the player to be able to set their own name, as well as answer yes or no as to whether that name is correct. I did this by using a while loop. However, since the name is initialized inside the loop, I cannot use it outside. I was wondering if there was anyway to do so.

My code is probably very basic and messy. I apologize for that.

    Scanner input = new Scanner(System.in);
    String name;
    int nameRight = 0;

    while (nameRight == 0) {

        System.out.println("What is your name?");
        name = input.nextLine();

        System.out.println("So, your name is " + name + "?");
        String yayNay = input.nextLine();

        if (yayNay.equals("yes") || yayNay.equals("Yes")) {
            System.out.println("Okay, " + name + "...");
            nameRight++;

        } 
        else if (yayNay.equals("no") || yayNay.equals("No")) {

            System.out.println("Okay, then...");

        } 

        else {
            System.out.println("Invalid Response.");
        }

    }

So basically, I want String name to be initialized inside the loop, so I can use it outside the loop.


回答1:


The scope of a variable, limits the use of that variable to the scope it is defined in. If you want it used in a broader scope, declare it outside the loop.

However, since the name is initialized inside the loop, I cannot use it outside.

You have defined the variable outside the loop, so the only thing you need to do is to initialize it, as the error message you should get suggests.

String name = "not set";

while(loop) { 
     name = ...

     if (condition)
        // do something to break the loop.
}
// can use name here.

The basic problem is that the compiler cannot work out that the variable will be set in all possible code paths. There is two ways you can fix this without using a dummy value. You can use a do/while loop.

String name;
boolean flag = true;
do {
    name = ...
    // some code
    if (test(name))
        flag = false;
    // some code
} while(flag);

or drop the condition, as you don't need a counter.

String name;
for (;;) {
    name = ...
    // some code
    if (test(name)) {
       break;
    // some code if test is false.
}



回答2:


NO, it wouldn't be possible as the scope of the variable declared in the loop is limited to the loop. So the variable is not longer accessible.

while(i < 10){
    int x = 2;
    i++;
}

Now, the scope of x would be from the point at which it is defined to the end of the enclosing block. So the variable here would be created and destroyed 10 times if i starts from 0.




回答3:


First there's the "scope", this is the issue you're touching at the moment. The way you have done this so far seems to be a good way of doing it and you WILL be able to use/access the name variable from anywhere in the code after line 2 from what you have linked.

The scope basically says, you can use the variable inside the curly brackets {} that you DECLARED it inside. I assume that you have your code inside some main method at the moment, thus you can access the name variable from anywhere after the line

String name;

as long as you don't try to use it after the closing }, corresponding to a opening { that occurred before name is declared.

SOLUTION: What you have to do to use a variable outside a loop, is to declare it before the loop begins, you don't have to initialize the variable before, but you have to initialize it before you try to use it for anything. In general, if you need to access the variable in a wider area, you must declare that variable before you enter the not-so-wide area.

Notice that by declaring I mean creating the variable reference by using "String" in front of "name". Don't confuse it with initializing it or assigning a value to it, that has nothing to do with the scope, only declaration sets the scope.



来源:https://stackoverflow.com/questions/35885718/java-is-it-possible-to-use-a-variable-outside-a-loop-that-has-been-initialised

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!