Scanner method opened and closed twice

人盡茶涼 提交于 2019-11-28 12:50:58

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!