有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何修复无法解析从未使用过的符号和变量的错误

我是java新手,这是我的第一个程序,我对这些错误感到非常困惑,并且到处寻找答案。请帮忙


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

然后它给了我这些错误,我用的是IntelliJ idea

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

共 (1) 个答案

  1. # 1 楼答案

    Cannot resolve symbol 'ans'

    在if之外声明ans

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

    否则,它在System.out.println中使用的行中永远不可见

    Variable 'ans' is never used

    Variable 'ans' is never used

    在你的代码中,ans是在if-code块中声明的,在赋值之后,那些ans就不再被使用了,因为if中的代码块就在赋值之后结束