运行时扫描变量时出错

Errors in scanning variables at runtime

提问人:Harsha Bharadwaz 提问时间:6/17/2018 最后编辑:Harsha Bharadwaz 更新时间:6/17/2018 访问量:21

问:

我是 Java 编程的初学者。我想求解表单的表达式 (a+2 0b)+(a+2 0 b+2 1 b)+........+(a+20b+...+2(n-1)b) 对于每个查询,以 a、b 和 n 的形式给出“q”查询,打印与给定的 a、b 和 n 值对应的表达式值。这意味着
样本输入:2
0 2 10
5 3 5
样本输出:4072
196

我的代码是:


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

}
编译器错误 表达式 java.util.scanner unresolved-external

评论

0赞 Mattia Righetti 6/17/2018
a并且仅在 for 循环中声明,因此它们在循环之外不可见。在 for 循环之外声明它们。同样的情况也是如此bn

答:

1赞 Mattia Righetti 6/17/2018 #1

这里的错误是声明 ,在循环中,这意味着当循环结束时,变量也将丢失,垃圾收集器将处理它们。abnfor

解决这个问题非常简单

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

评论

0赞 Harsha Bharadwaz 6/17/2018
非常感谢。但是我在同一行中遇到了一个新错误,说“局部变量 a 和 b 以及 n 可能尚未初始化”。该怎么办?
0赞 Mattia Righetti 6/17/2018
在初始化这 3 个变量时,为它们赋值,这样,如果扫描程序无法读取某个值,该变量仍然可以在运行时使用