[英]How to resolve these errors
I have a program that adds 2 numbers in Java and outputs the sum. 我有一个程序,该程序在Java中将两个数字相加并输出总和。 (The numbers are input through keyboard).
(数字通过键盘输入)。 However, I have an error that I need help resolving.
但是,我有一个错误需要解决。 I'll explain the error after the code:
我将在代码后解释错误:
package com.sigma.java7;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Addition {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
do {
try {
System.out.println("Enter A :");
String numA = br.readLine();
int a = Integer.parseInt(numA);
break;
} catch (Exception e) {
System.out.println("Incorrect input. Please enter an integer.");
}
} while (true);
do {
try {
System.out.println("Enter B :");
String numB = br.readLine();
int b = Integer.parseInt(numB);
break;
} catch (Exception e) {
System.out.println("Incorrect input. Please enter an integer.");
}
} while (true);
System.out.println("The sum of the numbers is: " +(a+b));
br.close();
}
}
In the line 在行中
"System.out.println("The sum of the numbers is: " +(a+b));"
I'm getting the errors: "a cannot be resolved to a variable and b cannot be resolved to a variable." 我收到错误消息:“ a无法解析为变量,b无法解析为变量。” WHY?
为什么?
You have bad variable scope. 您的变量作用域不好。 When you define local variables it will work only work in a same block.
定义局部变量时,它将仅在同一块中起作用。 ex.
恩。
{
int i = 2;
{
int k = 4;
// i can be accessed here.
}
// i can be accessed here.
// k can not be accessed here.
}
That's a compile time error caused by variable scope issues: a is defined inside the first try block, and is thus not visible outside that block. 这是由变量作用域问题引起的编译时错误 :a在第一个try块内定义,因此在该块外不可见。
As this has an assignment smell just a tip: move it to an outer scope and your problem will be solved.. 由于这有一个任务的气味,只有一个提示:将其移至外部示波器,您的问题将得到解决。
在外部作用域中定义a和b,以便在打印时可以访问它。
Before you first do while loop add: 在您第一次执行while循环之前,添加:
int a,b;
This will declare the variables to have scope outside of the loops so you can access them anywhere inside the method, instead of just a local loop. 这将声明变量在循环外部具有作用域,因此您可以在方法内部的任何位置访问它们,而不仅仅是局部循环。 If you add this line of code, replace
如果添加此行代码,请替换
int a = Integer.parseInt(numA);
with: 有:
a = Integer.parseInt(numA);
and the same thing for b 和b一样
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.