我不是使用import语句,而是使用java.util.Scanner类的extends属性。下面的代码段出现错误。如何更正它?
class test extends java.util.Scanner {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value from keyboard:");
int ans = sc.nextInt();
System.out.println("The value entered through keyboard ::"+ans);
}
}
答案 0 :(得分:1)
简短的答案:您不能这样做,因为java.util.Scanner是最终版本,您无法扩展它。
但是,您可以按照以下方式使用封装,在同一程序包中创建一个新类MyScanner:
import java.io.InputStream;
import java.util.Scanner;
public class MyScanner implements Iterator<String>, Closeable {
private Scanner scanner;
public MyScanner(InputStream in) {
this.scanner = new Scanner(in);
}
//Override classes you need
}
并在您的班级中使用它:
import java.io.InputStream;
import java.util.Scanner;
public class MyScanner {
private Scanner scanner;
public MyScanner(InputStream in) {
this.scanner = new Scanner(in);
}
public int nextInt() {
return scanner.nextInt();
}
}
请注意,这里的解决方案是在同一包中声明两个类
答案 1 :(得分:0)
由于Scanner
类已经结束,因此无法扩展。
即使有可能,扩展Scanner
也不允许您在引用无包名的import
类时消除Scanner
语句。
为给定代码扩展Scanner
是没有意义的。如果要避免使用import
语句,请使用完整的类名:
class test
{
public static void main(String[] args)
{
java.util.Scanner sc = new java.util.Scanner(System.in);
System.out.println("Enter the value from keyboard:");
int ans = sc.nextInt();
System.out.println("The value entered through keyboard ::"+ans);
}
}
答案 2 :(得分:0)
Scanner
是final
类,因此无法扩展。
如果要使用扫描仪而不显式导入扫描仪,则可以尝试以下操作:
class Test
{
public static void main(String[] args)
{
java.util.Scanner sc = new java.util.Scanner(System.in); // Specify full class path over here
System.out.println("Enter the value from keyboard:");
int ans = sc.nextInt();
System.out.println("The value entered through keyboard ::"+ans);
}
}
请记住命名约定:类名应以大写字母开头。