简体   繁体   English

JAVA:是否可以在循环内初始化的循环外使用变量?

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

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. 我是通过使用while循环完成的。 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. 基本上,我希望在循环中初始化String name,所以我可以在循环外部使用它。

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. 您可以使用do/while循环。

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.
}

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. 现在,x的范围将从定义它的位置到封闭块的末尾。 So the variable here would be created and destroyed 10 times if i starts from 0. 因此,如果我从0开始,这里的变量将被创建和销毁10次。

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. 到目前为止,您完成此操作的方式似乎是一种很好的方法,您可以在第2行之后的代码中的任何位置使用/访问名称变量。

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 我假设你现在在一些main方法中有你的代码,因此你可以从行后的任何地方访问name变量

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". 请注意,通过声明我的意思是通过在“name”前面使用“String”来创建变量引用。 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. 不要将它与初始化或为其赋值相混淆,这与范围无关,只有声明才能设置范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 更改已在循环外声明的变量 - changing a variable that has been declared outside of a loop 在循环外使用for循环内的变量 - use a variable from inside a for loop, outside of the loop 为什么不能调用已在循环中初始化并事先声明的变量? - Why can't you call a variable that has been initialised in a loop and declared beforehand? 如何使用已在for循环中初始化的变量? - How to use a variable that has been initialized in the for loop? 如果声明是在主方法中进行且在循环内部进行初始化,则在Java中无法从For循环外部访问变量吗? - Is variable when accessed from outside the For loop is not possible in Java if declaration is done in main method & initialization inside loop? Java-for循环内外的访问变量 - Java - Access variable inside and outside of for-loop 我想在 JAVA 的 FOR 循环之外使用一个变量 - I want to use a variable outside a FOR loop in JAVA Java:为什么在 for 循环外设置的变量会在 for 循环内发生变化 - Java: Why would a variable set outside of a for loop change inside of the for loop Java:循环内变量的几种可能类型 - Java: Several possible types for a variable inside of a loop 是否可以在 Java 的 while 循环中分配变量 - Is it possible to assign a variable inside a while loop in Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM