How can I access a scanner from another class?

Member Avatar for coil

You can code a get method that returns the Scanner.

You can code a get method that returns the Scanner.

can u show some syntax for that? im new to java

Member Avatar for coil

The structure for a method (in general) looks like this:

[access specifier] [return type] <method name> ( parameters go here... ) {
method body
}

So, for example:

public void doNothing() {
}

That would be an empty method that, as the name suggests, does nothing, takes no parameters, and returns void, or nothing.

A slightly more useful method:

private int returnSum(int a, int b) {
return a+b;
}

This takes two int parameters (you must supply two int parameters when calling the method, otherwise you get an error), and it returns an int. Note that this method is private.

A get method is basically a method that returns something - no special syntax required. In your case, it should return a Scanner.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.