简体   繁体   中英

How can I use the variables used inside a for loop outside the loop?

In the code below,I want to use variables a,b and n outside of the for loop where they are initially declared.for eg:in int S=a+b,the compiler cannot find the location of a and b.How can I do that?

    {

        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        for (int i = 0; i < t; i++) {
            int a = in.nextInt();
            int b = in.nextInt();
            int n = in.nextInt();
        }

        in.close();
        int S = a + b;
        for (int q = 1; q < n - 1; q++) {
            S = S + 2 ^ q;
            System.out.print(S + " ");

        }
    }
}

Short answer, you can't.

A workaround for your case is to store the values of those variables inside an array or map, this way you can use it from outside the loop (of course it needs to be declared outside the loop)

Just declare the variables in the same scope you want to use them in.

{

    Scanner in = new Scanner(System.in);
    int t = in.nextInt();
    int a;
    int b;
    int n;
    for (int i = 0; i < t; i++) {
        a = in.nextInt();
        b = in.nextInt();
        n = in.nextInt();
    }

    in.close();
    int S = a + b;
    for (int q = 1; q < n - 1; q++) {
        S = S + 2 ^ q;
        System.out.print(S + " ");

    }
}

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