扫描仪方法打开和关闭两次 [英] Scanner method opened and closed twice

查看:204
本文介绍了扫描仪方法打开和关闭两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在单个班级中,我有两种使用扫描仪类的方法。我为第一个方法创建了一个新的scanner对象实例,然后在第一个方法的末尾关闭它...然后在第二个方法中创建一个对象的新实例(具有不同的名称),最后在这个方法结束了。

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();
}


推荐答案

您应该将Scanner声明为类变量,因为您已经在方法gameSetup()中关闭了扫描程序。例如:

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.

这篇关于扫描仪方法打开和关闭两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆