A.D. A.D. - 3 years ago 183
Java Question

Can I use Scanner as method parameter?

I am taking a course on my own pace, the course was held last year and I can't find any materials on Git from people who did it already in order to compare, nor can I ask someone, so I would like to ask if you have an idea what they might mean. So I need to create different classes, one of which is Address and another is House. Now, both have the following method:

public static Address read(Scanner sc)
public static House read(Scanner sc)

The condition for the Address method is:
Pre: The next line retrieved by sc contains a textual representation of an Address.

Post: Transforms the textual representation of the Address into an
Address object.

I have the following simple implementation:

public static Address read(Scanner input) throws IOException {
String street = input.next();
int number = input.nextInt();
String zip = input.next();
String city = input.next();

Address address = new Address(street,number,zip,city);
return address;

For the same method in House, condition and tip:

Pre: The next lines retrieved by sc contains a textual representation
of a House.

Post: Transforms the textual representation of the House into a House

Hint: Make use of the read method in Address.

I am not sure how to implement this and I am sure it's something easy. But somehow I need to be able to receive the whole Address object via Scanner? And then parse it together with other textual input into a House object.
Any ideas? Thanks in advance.

I saw THIS thread, but it's not what I am asking for.

mix mix
Answer Source
public static House read(Scanner sc) throws IOException {
    sc.next(); //load house informations, i don't know how your file looks like

    Scanner addressSc = new Scanner(new File(/* address file path */));
    Address address = Address.read(addressSc);

    House house = new House(address, /* other parameters */);

Something like this could do the job. However I don't know how is your House class implemented and how your files are organized or where do you want to create House instance.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download