0

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

}
  • `a` and `b` are declared just in the for loop, so they won't be visible outside of it. Declare them outside of the for loop. Same goes for `n` – Mattia Righetti Jun 17 '18 at 11:26

1 Answers1

1

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();
}
Mattia Righetti
  • 1,265
  • 1
  • 18
  • 31
  • Thank you so much. But I've got a new error at the same lines saying that "the local variable a and b and n may not have been initialized". What to do? – Harsha Bharadwaz Jun 17 '18 at 11:48
  • Assign a value to those 3 variables when you initialise them, so that if the Scanner fails to read a value the variable can still be used during runtime – Mattia Righetti Jun 17 '18 at 12:10