简体   繁体   中英

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? Thanks!

The field is fine, except for the fact that it is static . You will need to remove the static modifier.

public Scanner scanner;

You will then be able to use the scanner object like normal. Remember that it may be null if the empty constructor is called rather than the non-empty constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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