Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
688 views
in Technique[技术] by (71.8m points)

java - Can't use Scanner class, constructor is undefined, method is undefined

When i want import scanner class in my project eclipse show me some errore :

 Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
  The constructor Scanner(InputStream) is undefined
  The method nextLine() is undefined for the type Scanner

and this is my code :

import java.util.Scanner;

public class Scanner {

    public static void main(String[] args) {

        Scanner myScanner = new Scanner(System.in);
        System.out.println(myScanner.nextLine());

    }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that you're also declaring a class called Scanner. That means that when you then declare a variable of type Scanner and try to call the constructor, the compiler thinks you're talking about your class. Just change your own class to something else (e.g. Test):

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner myScanner = new Scanner(System.in);
        System.out.println(myScanner.nextLine());
    }
}

Alternatively you could just fully-qualify the name when you mean java.util.Scanner - but this would be a bad idea in terms of readability.

// Please don't do this - but it would work.
public class Scanner {
    public static void main(String[] args) {
        java.util.Scanner myScanner = new java.util.Scanner(System.in);
        System.out.println(myScanner.nextLine());
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...