Ryan Miller
Ryan Miller

Reputation: 1

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

Upvotes: 0

Views: 35

Answers (3)

Aragorn
Aragorn

Reputation: 5289

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];

Upvotes: 1

Juan
Juan

Reputation: 1794

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];

Upvotes: 2

Vollmilchbb
Vollmilchbb

Reputation: 481

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.

Upvotes: 0

Related Questions