Search code examples
compiler-errorsexpressionjava.util.scannerunresolved-external

Errors in scanning variables at runtime


I'm beginner to Java programming. I want to solve an expression of the form (a+20b)+(a+20b+21b)+........+(a+20b+...+2(n-1)b) where you are given "q" queries in the form of a, b and n for each query, print the expression value corresponding to the given a, b and n values. That means
Sample Input:
2
0 2 10
5 3 5
Sample Output:
4072
196

My code was:

import java.util.Scanner;

public class Expression {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner in = new Scanner(System.in);
    int q=in.nextInt();
    for(int i=0;i<q;i++){
        int a = in.nextInt();
        int b = in.nextInt();
        int n = in.nextInt();
    }
    int expr=a+b;                 //ERROR:a cannot be resolved to a variable
    for(int i = 0; i<n;i++)       //ERROR:n cannot be resolved to a variable
        expr+=a+Math.pow(2, i)*b; //ERROR:a and b cannot be resolved to variables
    System.out.print(expr);
    in.close();
}

}

Solution

  • The error here is declaring a, b and n in the for loop, that means that when the loop ends the variables too will be lost and the garbage collector will take care of them.

    The solution to this is really easy

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in = new Scanner(System.in);
        int q=in.nextInt();
        int a, b, n;               // Declare outside if you need them outside ;)
        for(int i=0;i<q;i++){
            a = in.nextInt();
            b = in.nextInt();
            n = in.nextInt();
        }
        int expr=a+b;              //ERROR:a cannot be resolved to a variable
        for(int i = 0; i<n;i++) {  //ERROR:n cannot be resolved to a variable
            expr+=a+(2*i)*b;       //ERROR:a and b cannot be resolved to variables
            System.out.print(expr);
        }
        in.close();
    }