Error "cannot find symbol" เกิดขึ้นหลักเมื่อพยายามอ้างอิงตัวแปรที่ไม่ได้ประกาศในโปรแกรมที่กำลัง compile หมายถึง compiler ไม่รู้จักตัวแปรที่เราอ้างอิงถึง
สาเหตุที่เป็นไปได้ของ "Cannot find symbol"
- ใช้ตัวแปรที่ไม่ได้ประกาศ หรืออยู่นอก scope
- ใช้ case ผิด (เช่น "tutorials" และ "Tutorials" ต่างกัน) หรือสะกดผิด
- Packaged class ไม่ได้ถูกอ้างอิงถูกต้องด้วย import declaration
- ใช้ identifier values ผิด เช่น ตัวอักษร, ตัวเลข, underscore และ dollar sign เช่น hello-class ต่างจาก helloclass
ตัวอย่าง
public class CannotFindSymbolTest {
public static void main(String[] args) {
int n1 = 10;
int n2 = 20;
sum = n1 + n2;
System.out.println(sum);
}
}
Output
CannotFindSymbolTest.java:5: error: cannot find symbol sum = n1 + n2; ^ symbol: variable sum location: class CannotFindSymbolTest CannotFindSymbolTest.java:7: error: cannot find symbol System.out.println(sum); ^ symbol: variable sum location: class CannotFindSymbolTest
ในโปรแกรมข้างต้น Error "Cannot find symbol" จะเกิดขึ้นเพราะ "sum" ไม่ได้ประกาศ ในการแก้ไข ต้องกำหนด "int sum = n1+n2" ก่อนใช้ตัวแปร sum