简体   繁体   English

用Java构造和使用Scanner

[英]Construct and use Scanner in Java

I am looking at examples using Scanner to read a file (in Java). 我正在查看使用Scanner读取文件的示例(在Java中)。 In one example, the Scanner was constructed using: 在一个示例中, Scanner是使用以下命令构造的:

s = new Scanner(new BufferedReader(new FileReader("input.txt"))

But in another example the code is like below. 但是在另一个示例中,代码如下所示。 My question is that is there something wrong with the way Scanner was declared below? 我的问题是,下面声明Scanner的方式有问题吗? Do we not need to use the s = new Scanner(new BufferedReader(new FileReader("input.txt")) constructor? 我们是否不需要使用s = new Scanner(new BufferedReader(new FileReader("input.txt"))构造函数?

int howMany;
Scanner scan = null;
File f;
String[] words = null;

try {
    f = new File(filename);
    scan= new Scanner(f);
    howMany = scan.nextInt();
    words = new String[howMany];

    for (int i = 0; i < howMany; i++) {
        words[i] = scan.next();
    }
} catch (IOException e) {
    System.out.println(e);
}

There are multiple valid ways to construct a Scanner . 构造Scanner有多种有效方法。 Take a look at the documentation to see all of them. 查看文档以查看所有文档

There is nothing wrong with the approach that you have shown in your question. 您在问题中展示的方法没有错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM