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

Java入门代码编译报错求助:为何出现Scanner无法解析为类型错误

Fixing Unresolved Compilation Errors with Scanner in Java

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 21:17:29