Closing a Scanner throws java.util.NoSuchElementException

后端 未结 1 913
无人及你
无人及你 2020-11-28 15:28

I\'m writing an RPG combat system from scratch in Java, ambitious right? Well, I\'m having some trouble. This is my code:

void turnChoice() {
    System.out.         


        
相关标签:
1条回答
  • 2020-11-28 15:52

    When you are reading using Scanner from System.in, you should not close any Scanner instances because closing one will close System.in and when you do the following, NoSuchElementException will be thrown.

    Scanner sc1 = new Scanner(System.in);
    String str = sc1.nextLine();
    ...
    sc1.close();
    ...
    ...
    Scanner sc2 = new Scanner(System.in);
    String newStr = sc2.nextLine();      // Exception!
    
    0 讨论(0)
提交回复
热议问题