本文介绍了如何在Java中跨多个类使用同一扫描程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用多个类的程序,我希望其他类能够访问我在主类中声明的同一台扫描仪,我认为可以使用某种get方法来完成,但是我无法找到任何资源来帮助我。

I have a program that uses multiple classes, I want the other classes to be able to access the same scanner that I have declared in the main class, I assume it would be done using some sort of get method, however I am unable to find any resources to help me.

以下是我在我的主要课堂上制造的扫描仪:

Here are the Scanners that I have made in my main class:

  Scanner in = new Scanner(System.in);
            System.out.println("Enter a filename");
            String filename = in.nextLine();
            File InputFile = new File (filename);
            Scanner reader = new Scanner(filename);

阅读器扫描仪是我希望能够访问的其他类,程序,任何人都可以给我一些有关如何执行此操作的指导吗?非常感谢您的帮助!

The reader Scanner is the one I want to be able to access across the other classes that make up the program, can anyone give me some guidance on how I can do this? Thanks a lot for any help!

推荐答案

只需在= new Scanner(System中使用 public static final Scanner .in); 在您的 main 类中。
之后,您可以通过 MainClassName.in 在任何地方调用它。

Simply use public static final Scanner in = new Scanner(System.in); in you main class.After that you can call it from anywhere by MainClassName.in.

另外,请注意您传递给Scanner的参数。我想您想将 InputFile 放入 Scanner 而不是 filename =)

Also, be careful with arguments you pass to Scanner. I guess you wanted to put InputFile into Scanner, rather than filename =)

File InputFile = new File (filename);
Scanner reader = new Scanner(filename);

这篇关于如何在Java中跨多个类使用同一扫描程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 22:26