Compiler errors 运行时扫描变量时出错
我是Java编程的初学者。我想解一个形式的表达式 (a+20b)+(a+20b+21b)+……+(a+20b++……+2(n-1)b)如果以a、b和n的形式为每个查询提供“q”查询,则打印与给定a、b和n值对应的表达式值。这意味着Compiler errors 运行时扫描变量时出错,compiler-errors,expression,java.util.scanner,unresolved-external,Compiler Errors,Expression,Java.util.scanner,Unresolved External,我是Java编程的初学者。我想解一个形式的表达式 (a+20b)+(a+20b+21b)+……+(a+20b++……+2(n-1)b)如果以a、b和n的形式为每个查询提供“q”查询,则打印与给定a、b和n值对应的表达式值。这意味着 示例输入: 20210535 示例输出: 4072 196 我的代码是: import java.util.Scanner; public class Expression { public static void main(String[] args) {
示例输入:
2
0210
535
示例输出:
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();
}
}
import java.util.Scanner;
公共类表达式{
公共静态void main(字符串[]args){
//TODO自动生成的方法存根
扫描仪输入=新扫描仪(系统输入);
int q=in.nextInt();
对于(int i=0;i这里的错误是在for
循环中声明a
、b
和n
,这意味着当循环结束时,变量也将丢失,垃圾收集器将处理它们
解决这个问题真的很容易
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();
}
publicstaticvoidmain(字符串[]args){
//TODO自动生成的方法存根
扫描仪输入=新扫描仪(系统输入);
int q=in.nextInt();
int a,b,n;//如果需要在外部声明;)
for(int i=0;ia
和b
仅在for循环中声明,因此它们在for循环之外不可见。在for循环之外声明它们。非常感谢您。但是我在同一行中发现了一个新错误,即“局部变量a、b和n可能尚未初始化”。该怎么办?在初始化这3个变量时,为它们指定一个值,这样,如果扫描仪无法读取值,则在运行时仍可使用该变量