【问题标题】:Errors in scanning variables at runtime运行时扫描变量的错误
【发布时间】:2018-11-26 12:19:12
【问题描述】:

我是 Java 编程的初学者。我想解决形式的表达 (a+20b)+(a+20b+21b)+........+ (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();
}

}

【问题讨论】:

  • ab 仅在 for 循环中声明,因此它们在循环之外不可见。在 for 循环之外声明它们。 n 也是如此

标签: compiler-errors expression java.util.scanner unresolved-external


【解决方案1】:

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

解决这个问题真的很简单

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

【讨论】:

  • 非常感谢。但是我在同一行出现了一个新错误,说“局部变量 a 和 b 和 n 可能尚未初始化”。怎么办?
  • 在初始化时为这三个变量赋值,这样如果扫描器无法读取值,该变量仍然可以在运行时使用
猜你喜欢
  • 1970-01-01
  • 2017-03-15
  • 2017-07-08
  • 2017-05-15
  • 1970-01-01
  • 1970-01-01
  • 2018-03-30
  • 1970-01-01
  • 2020-04-06
相关资源
最近更新 更多