JAVA:是否可以在循环内使用已在循环内初始化的变量? [英] JAVA: Is it possible to use a variable outside a loop that has been initialised inside a loop?

查看:81
本文介绍了JAVA:是否可以在循环内使用已在循环内初始化的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名新程序员,试图通过制作游戏来练习.我希望播放器能够设置自己的名称,并回答该名称是否正确的是或否.我通过使用while循环来做到这一点.但是,由于名称是在循环内初始化的,因此我不能在外部使用它.我想知道是否还有这样做.

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.

推荐答案

变量的范围,将变量的使用限制在其定义的范围内.如果要在更广泛的范围内使用,请在外部声明循环.

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.

基本问题是编译器无法计算出将在所有可能的代码路径中设置变量的原因.有两种方法可以解决此问题,而无需使用伪值.您可以使用 do/while 循环.

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

这篇关于JAVA:是否可以在循环内使用已在循环内初始化的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆