Scanner objects in methods and NoSuchElementException [duplicate]

最后都变了- 提交于 2019-11-28 10:49:31

问题


This question already has an answer here:

  • java.util.NoSuchElementException - Scanner reading user input 2 answers

I have really tried to find the answer through the threads but still hope to get some feed back.

The code below is bad style I think but I don't know why it shoot me a java.util.NoSuchElementException after enter the number since I make two Scanner objects for two methods and I should be able to start a new input. And if I erase the input.close() in inputAndPrintNumber(), it works and compile correctly. I really hope to know why and how to fix it if I still use two Scanner obj and without erasing the input.close() if possible.

import java.util.*;
public class t{

public static void main(String [] args){
    inputAndPrintNumber();
    inputAndPrintString();
}

public static void inputAndPrintNumber(){
    Scanner input = new Scanner(System.in);
    String s = input.nextLine();        
    System.out.print(s);        
    input.close();
}

public static void inputAndPrintString(){
    Scanner input2 = new Scanner(System.in);
    int a = input2.nextInt();       
    System.out.print(a);
}
}

I don't even sure whether the code below is better or any better idea?

import java.util.*;

public class t{
public static Scanner input = new Scanner(System.in);
public static void main(String [] args){
    inputAndPrintNumber();
    inputAndPrintString();  
    input.close();
}

public static void inputAndPrintNumber(){
    String s = input.nextLine();        
    System.out.print(s);
}

public static void inputAndPrintString(){
    int a = input.nextInt();        
    System.out.print(a);
}
}

回答1:


When you call scanner.close() it not only closes scanner, but also stream from which it reads data, in this case System.in. So if you are going use System.in later don't close it (if it is closed, we can't reopen it and read any data from it, hence exception).

Your second code example solves this problem because Scanner is being closed when you are sure that nothing else will be read from input stream.

BTW it seems that you mixed places where nextLine and nextInt should be invoked (nextLine seems to be more appropriate for inputAndPrintString while nextInt for inputAndPrintNumber).



来源:https://stackoverflow.com/questions/27453298/scanner-objects-in-methods-and-nosuchelementexception

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