Print the value of i outside the for loop in java

后端 未结 2 1921
难免孤独
难免孤独 2020-12-22 10:32

I am trying to print/get the value of loop variable i and use it in another method outside the for loop. How do I do that?

public void mousePressed() {  
            


        
相关标签:
2条回答
  • 2020-12-22 10:43

    Variables declared in the for statement are in scope only in the for components and the following code block, see JLS section 14.14.1.1, in particular:

    for ( ForInit ; Expression ; ForUpdate ) Statement
    

    If the ForInit code is a local variable declaration, it is executed as if it were a local variable declaration statement (§14.4) appearing in a block.

    If you want to have it available outside the for, you have to declare it in a scope that is active in the location you want to access it; e.g. just outside the for loop:

    int i;
    for (i = 0; i < 1000; ++ i)
        ;
    // i is accessible in this scope
    System.out.println(i);
    

    Alternatively, if it is more appropriate, you could declare a separate variable and store the value of interest in it:

    int k = ...;
    for (int i = 0; i < 1000; ++ i)
        if (condition) // for example
            k = i;
    // k is accessible in this scope, i is not
    System.out.println(k);
    

    For a brief summary see this page, specifically the Loop Scope example at the end, which has an example that is exactly like your question.

    0 讨论(0)
  • 2020-12-22 10:43

    You can't, by definition the value of j is only available within this loop. But of course you could declare a variable outside this for loop and assign it to something within your loop. Exactly what value do you want it to be though? Since the value of your counter j at the end will always be the same.

    0 讨论(0)
提交回复
热议问题