Java入门代码编译报错求助:为何出现Scanner无法解析为类型错误
Hey there! Let's work through why your Java code is throwing those annoying compilation errors and fix them up.
First, let's recap the error you're seeing:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Scanner cannot be resolved to a type
scanner cannot be resolved to a type
at java_learning.main.main(main.java:7)
What's Going Wrong?
The Scanner class doesn't come in Java's automatically imported default package (java.lang). It lives in the java.util package, so your compiler has no clue what "Scanner" refers to unless you explicitly tell it where to find this class. That's exactly why you're getting those "cannot be resolved to a type" messages.
How to Fix It
Super easy fix—just add an import statement for Scanner right after your package declaration at the top of the file:
import java.util.Scanner;
Corrected Full Code
Here’s your code with the fix applied, plus a quick convention note (not required for fixing the error, but good practice for Java):
package java_learning; import java.util.Scanner; // Added this line to import Scanner // Pro tip: Java class names should start with a capital letter, so rename `main` to `Main` for standard practice public class main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("what is your name?"); String name = scanner.nextLine(); System.out.println("hello" + name); } }
Once you add that import line, your compiler will recognize the Scanner type, and the errors should disappear. Happy coding!
内容的提问来源于stack exchange,提问作者Mnfari

