Thalassophobia
Thalassophobia

Reputation: 21

Create only one Scanner object java

I'm trying to create one Scanner object to use in multiple places.

import java.util.Scanner;
private static Scanner keyboard;
public void doesSomething(String stringName){
    keyboard = new Scanner(System.in);
    ...
}

public static void main(String[] args){
    keyboard = new Scanner(System.in);
    ...
}

I previously tried using the new keyword in the creation of that instance variable but that didn't work because of some of the specifics of my code, but that's not my question. My question is simply- are these two Scanner objects or is this one object?

Upvotes: 2

Views: 2118

Answers (2)

Pshemo
Pshemo

Reputation: 124285

Each time you invoke new ... you are creating separate object. So if you invoke main once and lets say it will invoke doesSomething you will end up with two Scanner objects.

So remove keyboard = new Scanner(System.in); from doesSomething method since you don't really need it as this method already have access to keyboard field which will be initialized in main method.

You could also change keyboard from being field and lat it be local variable in main method. After that change let doesSomething method accept Scanner as argument

public void doesSomething(String stringName, Scanner keyboard){
    ...
}

public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    ...
    instance.doesSomething("something", sc);
    ...
}

and pass scanner you created in main method

Upvotes: 1

djechlin
djechlin

Reputation: 60848

Each time you run doesSomething you will create a new Scanner, forget about the old one stored in keyboard if there is one (it will late be garbage collected), and proceed. main will also create a new Scanner and put it in keyboard.

You will not be closing the old Scanner, which is a resource leak (i.e. it's bad so you don't want to create a zillion Scanners and throw them away improperly).

Upvotes: 1

Related Questions