简体   繁体   English

在for循环中初始化变量

[英]Initialising variables inside for loop

I have a for loop, and I initialise the variables inside that loop. 我有一个for循环,并且初始化了该循环中的变量。 After it, I need to manipulate that variables, but the compiler says that variables are not initialised . 之后,我需要操纵这些变量,但是编译器说变量没有初始化

public class Solution {
    static void displayPathtoPrincess(int n, String[] grid) {
        String[][] visual = new String[n][n];
        for (int i = 0; i < n; i++) {
            char[] myGrid = grid[i].toCharArray();
            for (int j = 0; j < n; j++) {
                visual[i][j] = myGrid[j] + "";
            }
        }

        int pX;
        int pY;
        int bX;
        int bY;
        // rescue the princess
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (visual[i][j].equals("p")) {
                    pX = j;
                    pY = i;
                }
                if (visual[i][j].equals("m")) {
                    bX = j;
                    bY = i;
                }
            }
        }
        System.out.println(pY + "");
        System.out.println(pX + "");
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int m;
        m = in.nextInt();
        String grid[] = new String[m];
        for (int i = 0; i < m; i++) {
            grid[i] = in.next();
        }

        displayPathtoPrincess(m, grid);
    }
}

if condition is true at some point. if条件在某些时候为true In fact if I move the print statements inside the if it works. 实际上,如果我将打印语句移动到的范围内, if可行。
How can solve this problem? 如何解决这个问题?

If you want to initialize your variables in conditions, then you need to set them to a default value : 如果要在条件中初始化变量,则需要将它们设置为默认值:

int pX = 0;
int pY = 0;
int bX = 0;
int bY = 0;

That way, your compiler will not return the initialization issue any more. 这样,您的编译器将不再返回初始化问题。

EDIT 编辑

I made some modifications, since I could not make your code work (cast from string to int, array of char initialization issue, etc.). 我做了一些修改,因为我无法使您的代码正常工作(从字符串到int的转换,char初始化数组的问题,等等)。 Could you try this please : 你可以试试这个吗:

public class Solution {
static void displayPathtoPrincess(String grid) {
    int n = grid.length();
    String[][] visual = new String[n][n];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            visual[i][j] = String.valueOf(grid.charAt(j));
        }
    }

    int pX = 0;
    int pY = 0;
    int bX;
    int bY;
    // rescue the princess
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (visual[i][j].equals("p")) {
                pX = j;
                pY = i;
            }
            if (visual[i][j].equals("m")) {
                bX = j;
                bY = i;
            }
        }
    }
    System.out.println(pY + "");
    System.out.println(pX + "");
}

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String grid = in.next();

    displayPathtoPrincess(grid);
}

It probably isn't what you want to do, but I have no problem with your variables' values initialized in conditions. 这可能不是您要执行的操作,但是对于条件中初始化的变量的值我没有问题。

you could try this 你可以试试这个

class Demo
{
static int pX;
static int pY;
static int bX;
static int bY;

public static void main(String a)
{
for (int i = 0; i < n; i++) {
    for(int j = 0; j < n; j++) {
        if (visual[i][j].equals("p")) {
            pX = j;
            pY = i;
        }
        if (visual[i][j].equals("m")) {
            bX = j;
            bY = i;
        }
    }
}
System.out.println(pY + "");
System.out.println(pX + ""); 
}

}

Below excerpt from JLS §16 (Definite Assignment) 以下摘录自JLS§16(确定分配)

For every access of a local variable or blank final field x, x must be definitely assigned before the access, or a compile-time error occurs. 对于每次访问局部变量或空白的最终字段x,必须在访问之前明确分配x,否则会发生编译时错误。

If you using a local variable at any point in your method, and compiler is not sure that local variable would be initialized when actually running the program then compiler will show error that please initialize local variable. 如果您在方法的任何位置使用局部变量,并且编译器不确定在实际运行程序时是否会初始化局部变量,则编译器将显示错误,请初始化局部变量。

In you case, if n is 0 then your for (int i = 0; i < n; i++) { loop will never run, so compiler cannot be sure that at this point System.out.println(pY + ""); 在您的情况下,如果n为0,则for (int i = 0; i < n; i++) {循环将永远不会运行,因此编译器无法确定此时System.out.println(pY + ""); , pY would be in initialized state, so complains. pY处于初始化状态,因此抱怨。

For solution: You must initialize local variable before using/reading it. 解决方案:使用/读取本地变量之前,必须对其进行初始化。

You are able to print pX and pY because compiler is sure at this point that values would be initialized, however try below and even in your IF block you will see that there is compilation error because you would be trying to read the local variables before they were initialized, so compiler complains. 您可以打印pXpY因为此时编译器确定会初始化值,但是请尝试以下操作,甚至在IF块中也将看到编译错误,因为您将尝试读取局部变量,然后再读取它们被初始化,所以编译器抱怨。

So, bottom line - make compiler believe that local variable would have been initialized at that point, so initialize local variables before using them. 因此,最重要的是-使编译器相信本地变量将在那时进行初始化,因此在使用本地变量之前先对其进行初始化。

if (visual[i][j].equals("p")) {
                    System.out.println(pY + "");  //Compilation error because compiler is not sure if LV would be in initialized state.
                    pX = j;
                    pY = i;
                    System.out.println(pY + "");  //Happy compiler becuse it is sure that LV are just initialized.
                }

The compiler needs to see that the variables have been definitely assigned regardless of which path through the loop the execution actually takes at runtime. 编译器需要确保变量已明确分配,无论执行在运行时实际通过循环的哪条路径。

It doesn't know if either of the if branches will run when your program executes. 它不知道程序执行时是否会运行if分支。

It is a good practice to always give your variables an initial value to avoid these kind of issues. 始终为您的变量提供初始值是避免此类问题的一种好习惯。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM