Skip to content
Advertisement

how to fix cannot resolve symbol and variable never used, errors

I am new to java and this is my first program, I’m very confused with these errors and have looked everywhere for the answer. please help!

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner myObj = new Scanner(System.in);

        System.out.println("Enter first number");
        String str1 = myObj.nextLine();

        System.out.println("Enter Operator");
        String op = myObj.nextLine();

        System.out.println("Enter second number");
        String str2 = myObj.nextLine();

        int num1 = Integer.parseInt(str1);
        int num2 = Integer.parseInt(str2);

        if (op.equals("+")) {
            int ans = (num1 + num2);
        } else if (op.equals("-")){
            int ans = (num1 - num2);
        }
        System.out.println(num1 + " " + op + " " + num2 + " = " + ans);
    }
}

Then it gives me these errors, I’m using IntelliJ idea

Cannot resolve symbol 'ans'
Variable 'ans' is never used
Variable 'ans' is never used

Advertisement

Answer

Cannot resolve symbol ‘ans’

Declare ans outside the if:

    int ans = 0; 
    if (op.equals("+")) {
        ans = (num1 + num2);
    } else if (op.equals("-")){
        ans = (num1 - num2);
    }
    System.out.println(num1 + " " + op + " " + num2 + " = " + ans);

otherwise it is never visible in the line where it is used in System.out.println

Variable ‘ans’ is never used

Variable ‘ans’ is never used

In your code ans is declared in the if – code blocks, and after assignment those ans are no longer used, because code-block in if ends just after the assignment.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement