学习Java4周,使用var局部变量类型推断编译时报‘Cannot find symbol’错误求助
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 -versionIf the output shows a version number less than 10 (e.g.,
1.8.0_XXXfor 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 likevar. After installing, make sure your system'sPATHenvironment variable points to the new JDK'sbindirectory (so Command Prompt uses the updatedjavacandjavacommands 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 VarDemoQuick alternative: Replace
varwith the explicit type
If you can't upgrade your JDK right now, just swapvarfor the actual type of your variable. In your code,avgis adouble, so rewrite that line as:double avg = 10.0;This will work with any Java version that supports basic variable declarations.
内容的提问来源于stack exchange,提问作者neo360

