无法使用Scanner类,构造函数未定义,方法未定义 [英] Can't use Scanner class, constructor is undefined, method is undefined
问题描述
当我希望在我的项目eclipse中导入扫描器类时显示一些错误:
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
这是我的代码:
import java.util.Scanner;
public class Scanner {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println(myScanner.nextLine());
}
}
推荐答案
问题在于,您还声明一个名为 Scanner
的类。这意味着当您然后声明一个类型为 Scanner
的变量,并尝试调用构造函数时,编译器会认为您正在谈论您的类。只需将自己的课程改成别的东西(例如 Test
):
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());
}
}
或者你可以当您的意思是 java.util.Scanner
时,可以完全限定名称,但这在可读性方面是一个坏主意。
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());
}
}
这篇关于无法使用Scanner类,构造函数未定义,方法未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!