You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

学习Java4周,使用var局部变量类型推断编译时报‘Cannot find symbol’错误求助

Fixing the "Cannot find symbol" Error with Java's var Keyword

Hey there! Let's break down why you're hitting that frustrating "Cannot find symbol" error when using var—it's a common gotcha when working with older Java versions.

First, let's clean up your code for readability:

class VarDemo {
    public static void main(String args[]) {
        var avg = 10.0;
        System.out.println("Value of avg: " + avg);
    }
}

The Root Cause

The var keyword for local variable type inference was introduced in Java 10. If you're compiling with a JDK version older than 10 (like Java 8, which is still widely used), the compiler has no idea what var is—hence the "Cannot find symbol" error.

How to Fix It

Here are straightforward solutions to get your code running:

  • Check your JDK version first
    Open Command Prompt and run these two commands to confirm your setup:

    java -version
    javac -version
    

    If the output shows a version number less than 10 (e.g., 1.8.0_XXX for Java 8), that's definitely the issue.

  • Upgrade to a newer JDK
    Grab a stable LTS (Long-Term Support) version like Java 11 or 17—they're well-supported and include all modern features like var. After installing, make sure your system's PATH environment variable points to the new JDK's bin directory (so Command Prompt uses the updated javac and java commands instead of the old ones).

  • Explicitly set the compilation version (if needed)
    If you've upgraded but still run into hiccups, you can tell the compiler to target Java 10+ directly when building:

    javac --release 10 VarDemo.java
    java VarDemo
    
  • Quick alternative: Replace var with the explicit type
    If you can't upgrade your JDK right now, just swap var for the actual type of your variable. In your code, avg is a double, so rewrite that line as:

    double avg = 10.0;
    

    This will work with any Java version that supports basic variable declarations.

内容的提问来源于stack exchange,提问作者neo360

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:59:39