Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/399.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在不同类中创建两个扫描仪_Java_Java.util.scanner - Fatal编程技术网

Java 在不同类中创建两个扫描仪

Java 在不同类中创建两个扫描仪,java,java.util.scanner,Java,Java.util.scanner,我目前在我的项目中在两个不同的类中使用两个不同的扫描器:它们都接受做不同事情的用户输入。调用第一个扫描器正常工作,但当我尝试调用第二个扫描器时,即使在我关闭第一个扫描器之后,它也会将输入注册为null 第一类 Scanner scan = new Scanner(System.in); public void foobar(){ System.out.println("Enter data: "); String foo = scan.next(); scan.close

我目前在我的项目中在两个不同的类中使用两个不同的扫描器:它们都接受做不同事情的用户输入。调用第一个扫描器正常工作,但当我尝试调用第二个扫描器时,即使在我关闭第一个扫描器之后,它也会将输入注册为null

第一类

Scanner scan = new Scanner(System.in);
public void foobar(){
    System.out.println("Enter data: ");
    String foo = scan.next();
    scan.close();
    class2.function(foo);
}
第二类

Scanner scan1 = new Scanner(System.in);
public void foobar1(String foo){
    System.out.println("Enter more data: ");
    String fooo = scan1.Next();
    //Automatically prints null here and closes program
}
我应该只使用一台扫描仪吗?还是以其他方式使用Scanner类?谢谢

scan.close()
还关闭
系统。在
中,这样就不能从流中读取更多数据。因此,当您开始从
scan1
读取时,
System.in
将不再返回任何数据

因此,如果对所有实例使用相同的输入流,则在完成所有扫描之前,不要关闭任何
扫描仪
实例

有关更多信息,请查看的文档

关闭此扫描仪如果此扫描仪尚未关闭,则如果其底层readable也实现了Closeable接口,则将调用readable的close方法。

如果您查看的文档,您可以看到它确实实现了
可关闭的
界面

因此,将调用并关闭
InputStream
,从而使您没有可从中读取数据的输入流

关闭此输入流并释放与该流关联的所有系统资源

scan.close()
还关闭
系统。在
中,这样就不能从流中读取更多数据。因此,当您开始从
scan1
读取时,
System.in
将不再返回任何数据

因此,如果对所有实例使用相同的输入流,则在完成所有扫描之前,不要关闭任何
扫描仪
实例

有关更多信息,请查看的文档

关闭此扫描仪如果此扫描仪尚未关闭,则如果其底层readable也实现了Closeable接口,则将调用readable的close方法。

如果您查看的文档,您可以看到它确实实现了
可关闭的
界面

因此,将调用并关闭
InputStream
,从而使您没有可从中读取数据的输入流

关闭此输入流并释放与该流关联的所有系统资源


无需创建两个扫描仪,您可以使用相同的
扫描仪
,因为一旦扫描关闭,流
系统也将关闭。
比如:

其中:

public void function(String foo,Scanner scan1){
    System.out.println("Enter more data: ");
    String fooo = scan1.next();
    System.out.println(fooo);
}

但是,如果需要创建两个扫描仪,请使用
scan.reset()而不是
scan.close()
在class1中

无需创建两个扫描仪,您可以对这两个扫描仪使用相同的
扫描仪
,因为一旦扫描关闭,流
系统也将关闭。
比如:

其中:

public void function(String foo,Scanner scan1){
    System.out.println("Enter more data: ");
    String fooo = scan1.next();
    System.out.println(fooo);
}

但是,如果需要创建两个扫描仪,请使用
scan.reset()而不是
scan.close()scan.reset()而不是
scan.close()你能告诉我你为什么需要这个吗?也许可以创建一个有扫描仪的类,让其他类扩展这个类?使用
scan.reset()而不是
scan.close()谢谢!这很有道理,谢谢你!这很有道理这也很有道理!谢谢下次我一定会用这个。这也很有意义!谢谢下次我一定会用这个。