user2556208
user2556208

Reputation:

Scanner method opened and closed twice

In a single class I have two different methods who are using the scanner class. I created a new instance of scanner object for the first method, then closed it at the end of the first method...then created a new instance of an object (with a different name) in the second method to finally close it at the end of this method.

Unless I open the scanner once and close it once it won't work and return an error. The double use of the scanner class doesn't seem to work. What am I doing wrong?

Here are my two methods which return an error...

public void GameSetup(){
    //intro to the program and what the user should expect to do
    Scanner in = new Scanner(System.in);
    out.println("Let's play a little baseball game. Type down the scores for each team at the end of each inning to determine the winner!" +
            "\nFor each inning enter the score for the first team, hit space and enter the score for the second team.\nFirst, let's enter the team names:");

    //Console will ask for the team names.
    out.println("What is the name of team 1?");
    team1Name = in.nextLine(); //Read team name 1
    out.println("What is the name of team 2?");
    team2Name = in.nextLine(); //Read team name 2
    in.close();//close the scanner
}


public void GetScores() {//this method will make the console ask for the scores for each innings

    Scanner input = new Scanner(System.in);
    out.println("What is the score at the end of 1st inning? (team 1 score <space> team 2 score)"); //The console asks to enter scores for each team
    team1Array[0] = input.nextInt(); //Read an integer for team 1 inning 1
    team2Array[0] = input.nextInt(); //Read an integer for team 2 inning 1
    out.println("What is the score at the end of 2nd inning? (team 1 score <space> team 2 score)"); 
    input.close();
}

Upvotes: 2

Views: 26683

Answers (3)

kurt_hilder
kurt_hilder

Reputation: 1

I have been learning Java for a short time and don't really know what I am doing, but this worked for me. I have no idea why it did but...

import java.util.Scanner;
public class Inputing{

    public Scanner input_scan = null;

    public static int ScanningInput() {
        int input_value = 0;
        Scanner input_scan = new Scanner(System.in);

        try {
            input_value = input_scan.nextInt();
        } catch (Exception e) {
            System.out.println("!error!");
        } finally {
            if (input_scan.equals(null)) {
                input_scan.close();
            }
        }
        return input_value;
    }

    public static int getInputA(int scan_valueA){
        scan_valueA = (ScanningInput());
        return scan_valueA;
    }

        public static int getInputB(int scan_valueB){
        scan_valueB = (ScanningInput());
        return scan_valueB;
    }
}

// then call it with another class

public class MainClass{

    public static void main(String[] args) {

        int variableA = 0; 
        variableA = Inputing.getInputA(variableA);

        int variableB = 0;
        variableA = Inputing.getInputC(variableB);
    }

}

I apologize for any errors, and would appreciate guidance. I am a complete rookie but after messing with this code for a while, this seemed to produce no warnings and return the results I was looking for.

Upvotes: 0

HCL02
HCL02

Reputation: 86

You should declare Scanner as a class variable because you're already closing the scanner in the method gameSetup(). example:

 public class Game{
        Scanner in = new Scanner(System.in);

        public void GameSetup(){
            //insert code here DO NOT CLOSE SCANNER....
        }


        public void GetScores() {
            //your code here.........
            in.close();
        }
 }

Or else what you can do is declare a scanner in each method and close in scope.

Upvotes: 0

Reimeus
Reimeus

Reputation: 159844

As both Scanner instances use the same InputStream source, when the first instance is closed, then the second instance is unable to read from the InputStream resulting in a NoSuchElementException.

public class GameClass {
    private final Scanner input;

    public GameClass() {
         input = new Scanner(System.in);
    }

    public void getScores() {
         team1Array[0] = input.nextInt();
         ...
    }
}

There's no need to close the Scanner instances unless you wish it to fail for subsequent reads. You could use a single instance of Scanner to avoid the overhead of 2 instances. By not closing the Scanner you also improve testability of the class.

Upvotes: 6

Related Questions