compiler-errors - 运行时扫描变量时出错

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

我是Java编程的初学者。我想解决形式的表达
(a + 20b)+(a + 20b + 21b)+ ... +(a + 20b + ... + 2(n-1)b),其中以形式提供“q”查询每个查询的a,b和n中,打印与给定的a,b和n值相对应的表达式值。那意味着
输入样例:
20 2 105 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();
}

}

最佳答案

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

解决方案非常简单

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

关于compiler-errors - 运行时扫描变量时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50896146/

相关文章:

C++11:decltype((x)) 和 decltype((x+1)) 的类型不同?

c# - C# 编译器在翻译 LINQ 表达式时如何选择 SelectMany?

java - 返回文本文件中单词出现的所有行号的方法

OpenCV linemod 不是 cv 成员

c++ - 在 C++ 程序中使用 ANTLR3

python - “模块”不能用 numba 的 jit 编译器调用

java - 输入为空时如何返回语句?

java - 循环扫描仪输入后无法打印行 - Java

git - 移动git项目导致许多Blob和树错误

c++ - 如何在C++文件中声明标识符JSON?