简体   繁体   English

java-如何在字段和构造函数中使用扫描器?

[英]java- How to use scanner in fields and constructors?

Okay so here's what I have to do. 好的,这就是我要做的。

Scanner data = new Scanner(new File("moby.txt"));
CharacterCounter empty = new CharacterCounter();        // provide default constructor, initialize all Class fields
CharacterCounter working = new CharacterCounter(data);  // reads data from file, contains all the code to read file

So I have to make a class that will end up counting characters. 因此,我必须创建一个最终要计算字符数的类。 I have a good idea of how to do that, I am just struggling with making fields/constructors. 我对如何做到这一点有一个很好的主意,我只是在努力使领域/构造函数。

I think I really just need to make a single field, with data. 我想我真的只需要在一个字段中添加数据即可。

This is what I have so far 这就是我到目前为止

//fields
public static Scanner scanner;
//constructors
public CharacterCounter(){

}
public CharacterCounter(Scanner input){
    this.scanner = input;
}

I don't believe I did the field right, nor the constructor right. 我不相信我做的是正确的领域,也不是构造函数的。 And I don't even know how to fill out the empty constructor. 而且我什至不知道如何填写空的构造函数。 Anyways, if I want to create methods to work with this Scanner data, how do I make a scanner field? 无论如何,如果我想创建使用此Scanner数据的方法,该如何创建一个Scanner字段? Thanks! 谢谢!

The field is fine, except for the fact that it is static . 该字段很好,除了它是static You will need to remove the static modifier. 您将需要删除static修饰符。

public Scanner scanner;

You will then be able to use the scanner object like normal. 然后,您将能够像平常一样使用scanner对象。 Remember that it may be null if the empty constructor is called rather than the non-empty constructor. 请记住,如果调用空构造函数而不是非空构造函数,则它可能为null。

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

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