简体   繁体   中英

How can I use variables that I find the value of in a loop outside of that loop?

I want to use row and col as the parameters of my 2d array but cannot because I cant find a way because my variables are local to there loop. My question is how can I make the values i find for row and col the parameters of my array.

int list [] [] = new int [row] [col];
    boolean done = false;
    while (done = false)
    {
        for (int counter = 3; counter <= 15; counter++)
        {
            if (num%counter == 0)
            {
                int row = counter ;
                int col = num/counter;
                done = true;
            }          
        }
    }

You need to declare them outside the loop:

    boolean done = false;
    int row = -1;
    int col = -1;
    while (done == false)
    {
        for (int counter = 3; counter <= 15; counter++)
        {
            if (num%counter == 0)
            {
                row = counter ;
                col = num/counter;
                done = true;
            }          
        }
    }
    int list [] [] = new int [row] [col];
boolean done = false;
int row = -1;
int col = -1;

while (done == false)
{
    for (int counter = 3; counter <= 15; counter++)
    {
        if (num%counter == 0)
        {
            row = counter ;
            col = num/counter;
            done = true;
        }          
    }
}
System.out.println(row + " " + col);
int list [] [] = new int [row] [col];

You can't do it unless you create a new array cause static arrays are kinda static. Of course you can switch to ArrayList to evade these kind of misunderstandings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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