0

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 + " ");

        }
    }
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • 3
    You can't. If you want to use variables outside of a loop, you must define them outside the loop. – azurefrog Jan 16 '20 at 21:56
  • You can't reference something outside of your current scope. As soon as the for loop ends, those variables and pointers are gone. If you want to use them elsewhere you have to change their scope, e.g. define them outside of the loop at whatever scope you need (method, class, etc.). – Liftoff Jan 16 '20 at 21:58
  • 1
    I indented your code according to brackets in it. This should let you see more problems in it. Anyway you already seem to know the answer to your question: declare those variables before loop, just like you already did for `int S`. Anyway aside from that, what is before first `{`? I hope not a loop because closing scanner will close System.in and prevent you from reusing it in next iterations. – Pshemo Jan 16 '20 at 21:58
  • [Scope](https://www.inf.unibz.it/~calvanese/teaching/05-06-ip/lecture-notes/uni03/node15.html) is not ***just*** a mouthwash. – Elliott Frisch Jan 16 '20 at 21:58
  • This will help: https://stackoverflow.com/a/38177231/8430155 – Harshal Parekh Jan 16 '20 at 21:59
  • As a side note, `2 ^ q` is probably not what you want to be adding here; this is a bitwise XOR, not 2 to the power of `q`. You can use `Math.pow` for exponentiation, or a bitwise shift `1 << q` for the special case of 2 to the power of `q`. – kaya3 Jan 16 '20 at 23:59

2 Answers2

0

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)

A.Oubidar
  • 391
  • 2
  • 10
0

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 + " ");

    }
}
David Newcomb
  • 10,639
  • 3
  • 49
  • 62