If you're a beginner (like me), the solution may be as simple as making sure the parent folder that the file you're working in is a Java project.
I made the mistake of simply creating a Java folder, then creating a file in the folder and expecting it to work. The file needs to live in a project if you want to avoid this error.