java.util.NoSuchElementException - Scanner reading user input

后端 未结 4 2073
灰色年华
灰色年华 2020-11-21 05:30

I\'m new to using Java, but I have some previous experience with C#. The issue I\'m having comes with reading user input from console.

I\'m running into the \"java.u

4条回答
  •  死守一世寂寞
    2020-11-21 05:37

    the reason of the exception has been explained already, however the suggested solution isn't really the best.

    You should create a class that keeps a Scanner as private using Singleton Pattern, that makes that scanner unique on your code.

    Then you can implement the methods you need or you can create a getScanner ( not recommended ) and you can control it with a private boolean, something like alreadyClosed.

    If you are not aware how to use Singleton Pattern, here's a example:

    public class Reader {
        
        
        private Scanner reader;
        private static Reader singleton = null;
        private boolean alreadyClosed;
        
        private Reader() {
            alreadyClosed = false;
            reader = new Scanner(System.in);
        }
        
        public static Reader getInstance() {
            if(singleton == null) {
                singleton = new Reader();
            }
            return singleton;
        }
        
        public int nextInt() throws AlreadyClosedException {
            if(!alreadyClosed) {
                return reader.nextInt();
            }
            throw new AlreadyClosedException(); //Custom exception
        }
        
        public double nextDouble() throws AlreadyClosedException {
            if(!alreadyClosed) {
                return reader.nextDouble();
            }
            throw new AlreadyClosedException();
        }
        
        public String nextLine() throws AlreadyClosedException {
            if(!alreadyClosed) {
                return reader.nextLine();
            }
            throw new AlreadyClosedException();
        }
        
        public void close() {
            alreadyClosed = true;
            reader.close();
        }   
    }
    
    

提交回复
热议问题