Reputation: 21
Can anyone tell me the reason why we declare a Scanner
class object a second time if we want to use it in a method outside the main method where it was first declared?
For example:
public static void main(String[] args) {
Scanner j = new Scanner(System.in);
String val = j.next();
}
static void lod() {
Scanner j = new Scanner(System.in);
String m = j.next();
}
Why should I declare the Scanner
class object again before using it in the method lod()?
Upvotes: 2
Views: 866
Reputation: 79435
... why we declare a scanner class object the second time if we want to use it in a method outside the main method?
You do not have to do it and it is also not a clean way to do it. I would use one of the following ways:
Declare the Scanner
object as an instance variable. However, you won't be able to use it directly inside a static
method (including main
) as you can't access a non-static
member inside a static
method directly. In a static
method, you will be able to access an instance variable only through the instance of the class e.g.
import java.util.Scanner;
public class MyClass {
Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
MyClass obj = new MyClass();
System.out.print("Enter a word: ");
System.out.println(obj.scanner.nextLine());
}
static void lod() {
MyClass obj = new MyClass();
String m = obj.scanner.next();
}
}
Declare the Scanner
object as a class variable (i.e. static variable at class level) e.g.
import java.util.Scanner;
public class MyClass {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter a word: ");
System.out.println(scanner.nextLine());
}
static void lod() {
String m = scanner.next();
}
}
Pass the Scanner
object to the methods being called from main
e.g.
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a word: ");
System.out.println(scanner.nextLine());
}
static void lod(Scanner scanner) {
String m = scanner.next();
}
}
Upvotes: 2
Reputation: 11
In Java the objects can be created inside methodsor outside and so they are only for that method or for the whole class but I don't recomend you to do that becouse every time the class is used the method is created even though you're accesing a method that don't uses it. Instead, you can declarate it outside the method and it will be accessible for all the methods from the class, but it will have to be created separately inside every method and they will be destroyed in the end of the method. Example:
class example{
Canstructor name;
public void method1(){
name = new Constructor();
}
public void method2(){
name = new Constructor();
}
}
Upvotes: 0
Reputation: 96
You don't need to! You can declare Scanner object at the class level like this,
class Test {
static Scanner j = new Scanner(System.in);
....
}
Upvotes: 1