在java中使用相同的扫描仪

在java中使用相同的扫描仪,java,java.util.scanner,filereader,Java,Java.util.scanner,Filereader,我可以使用扫描器读取用户输入的某个输入,然后创建一个新的实例来读取文件吗 Scanner sc = new Scanner(System.in); System.out.print("Enter the file name: "); String fileName = sc.next(); sc = new Scanner(fileName); displayAll(sc); //a static void method that takes the Scanner object as a p

我可以使用扫描器读取用户输入的某个输入,然后创建一个新的实例来读取文件吗

Scanner sc = new Scanner(System.in);
System.out.print("Enter the file name: ");
String fileName = sc.next();
sc = new Scanner(fileName);

displayAll(sc); //a static void method that takes the Scanner object as a parameter and is supposed to read and display the input stored in the .txt file

那么,您需要使用一个
文件

Scanner sc = new Scanner(System.in);
System.out.print("Enter the file name: ");
String fileName = sc.next();
sc = new Scanner(new File(fileName));
更安全的做法是
尝试捕获不存在的文件。如果需要,您可以使用
。好。。。逻辑取决于你。也许是这样的:

Scanner sc = new Scanner(System.in);
while (true) {
    System.out.println("Enter file name");
    String filename = sc.next();
    if (!filename.startsWith("sth")) {    //this will reask if the file name doesn't start with "sth"
        continue;
    try {
        Scanner s = sc; //just in case you never gonna use System.in
        sc = new Scanner(new File(filename));
        s.close(); //just in case you're sure you never gonna use System.in
        break;
    } catch (Exception e) {
        System.out.println("Wrong filename - try again");
    }
}

显然,您可以将
if
条件更改为您喜欢的任何条件。我只是想给你一个更广阔的视角。如果您希望ofc,您可以切换到
equals

您没有使用与问题标题中所述相同的
扫描仪。您正在创建
扫描仪的两个不同且独立的实例

代码中的sc
是扫描仪参考。首先,它引用第一个
扫描仪
对象。然后将对象引用更改为指向第二个
扫描仪
对象。您不是在重用
扫描仪
对象,而是在重用对象引用。这完全可以

创建
扫描仪
对象时,无法更改扫描仪使用的源。从其他源获取数据需要创建新实例

在您的代码示例中,您使用两个不同的扫描仪对
系统进行扫描的方法是很好的。但是,您的示例中的问题是,您对文件扫描程序使用了错误的构造函数。要使用文件作为源创建扫描仪,需要创建
文件
路径
对象,并将此对象用作构造函数参数,而不是文件名字符串:

new Scanner(new File(filename));
或:


是的,你可以。为什么不试试呢?如果找到匹配项,只需使用
,然后重新初始化scanner@PavneetSingh他有工作守则。如果文件名是具有扩展名的文件的路径,则work@xenterosOP说,
用户输入一个特定的输入
,然后创建一个新的实例从文件中读取
,看起来你也没有读我的评论,OP不想要这个,只需添加一个
if
条件即可满足OPrequirements@PavneetSingh是的,他补充道。小姐输入了测试版的答案。抱歉,m8I只需添加一个
扫描仪tmp=scnew Scanner(Paths.get(filename));