I have a program that adds 2 numbers in Java and outputs the sum. (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." 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.
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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.