简体   繁体   中英

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());

    }

}

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 (eg 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());
    }
}

Try

java.util.Scanner myScanner = new java.util.Scanner(System.in);

instead. Else the compiler tries to instantiate your class which is also called Scanner . Or just rename your own Scanner class to something else.

Please change the name of your class:

public class Scanner {

to some other name. The compiler is unable to see Scanner as java.util.Scanner because it sees it as your class (which doesn't have such constructor nor method so it gives you errors informing about it).

Try to change your class name eg:

import java.util.Scanner;

public class ScannerTest {

    public static void main(String[] args) {

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

    }

}

You should give class name as different then API classes of Java.So just change class name from Scanner to ScannerProgram .

import java.util.Scanner;

     public class ScannerProgram {

    public static void main(String[] args) {

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

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM