Results 1 to 13 of 13
Like Tree1Likes
  • 1 Post By kneitzel

Thread: Exception in thread "main" java.util.NoSuchElementException

  1. #1
    EBamber is offline Member
    Join Date
    Apr 2014
    Posts
    30
    Rep Power
    0

    Default Exception in thread "main" java.util.NoSuchElementException

    I'm trying to write an NLP module for an application (need to convert it to Android later), users can input more than one sentence in the code, it will be converted to a prolog query which will be processed and returned as variables for the other modules. However, when I input more than 1 sentence (apart from the second query possibly failing because of lack of words in the lexicon) I get this error in Java:

    Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1371)
    at gapt.LanguageProcessor.Directions(LanguageProcesso r.java:269)
    at gapt.LanguageProcessor.questionHandler(LanguagePro cessor.java:129)
    at gapt.LanguageProcessor.queryDecoder(LanguageProces sor.java:96)
    at gapt.LanguageProcessor.NLPquery(LanguageProcessor. java:80)
    at gapt.GAPT.main(GAPT.java:11)
    Java Result: 1

    (supposedly it's easy to fix so I'm posting it in here, but the code itself is quite complex so I was confused as to whether or not it would count as an advanced problem)

    Now, I've looked at other threads with the same problem on this forum and others and for the most part they say it's because the Scanner closed for the second input - but I didn't use the close() method on my Scanners in any part of the code so I'm lost

    Java Code:
    public void NLPquery(String x) //this method checks if the query posted by the user is valid
        {
        	String[] y = x.split("[\n.] ");
        	for(int i=0;i<y.length;i++)
        	{
                npt.add(y[i]); //each one a sentence
        	}
            //each sentence a list
            //for each, check number of words, make new list where each word is a new term
            for(int i = 0; i < npt.size(); i++)
            {
                String[] z = npt.get(i).split(" ");
                input.add(new ArrayList<>());
                for(int j=0;j<z.length;j++)
                {input.get(i).add(z[j]);}
                String S = "[";
                for (int j = 0; j<input.get(i).size();j++)
                {
            	S+=input.get(i).get(j);
                    if(j<input.get(i).size()-1)
                    {
                        S+= ",";
                    }
                }
                S+= "]";
                Query q2 = new Query("s(_,"+S+",[]).");
                check.add(q2.hasSolution());
            }  
            for(int i = 0; i<check.size();i++)
            {
                if(truth && check.get(i) == true)
                {
                    truth = true;
                }
                else 
                {
                    truth = false; i=check.size();
                }
            }        	
            if(truth == true)
            { 
            	//the query() method returns a boolean value based on the output of the query object instance created
            	// in this case, the JVM will be querying the GAPT.pl knowledge base if the input string is recognized by the grammar as a subset of "phr"
            	// in prolog query syntax, this would be: ?- phr(X,[]).
            	queryDecoder();
            }
            else response(false);
        }
    
    public void queryDecoder() //this method re-routes the program to the Handler of whatever kind of phrase was given by the user
        {
        	for(int i = 0; i < input.size(); i++)
        	{
                String[] S = new String[input.size()];
                Query q2 = new Query(new Compound("s", new Term[]{new Variable("X"),Util.stringArrayToList(input.get(i).toArray(S)),new Atom("[]")}));
                java.util.Hashtable solution;
                solution = q2.oneSolution();
                switch(solution.get("X").toString())
                {
            	case "command": {commandHandler(i); break;}
            	case "query": {questionHandler(i); break;}
            	default: break;
                }
        	}
        }
    
    public void questionHandler(int i)
        {
            //if map query pass control to map
            //if calendar query, query the calendar database and update if necessary
            //else query google
            String[] Y = new String[input.size()];
            Query q2 = new Query(new Compound("q", new Term[]{new Variable("X"),Util.stringArrayToList(input.get(i).toArray(Y)),new Atom("[]")}));
            java.util.Hashtable solution = q2.oneSolution();
            switch(solution.get("X").toString())
            {
            	case "dir": {Directions(); break;}
            	case "time": {Calendar("Query",i); break;}
            	default: break;
            }
        }
    
    public void Directions()
        {
            try ( //this method will create the parameters used in a map enquiry and call the method necessary
                    Scanner sc = new Scanner(System.in)) 
            {
                sc.useDelimiter("\n");
                System.out.println("What is the name of the location you want to find?");
                String name = sc.next();
                Map(name);
            }
        }

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,424
    Rep Power
    25

    Default Re: Exception in thread "main" java.util.NoSuchElementException

    Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1371)
    at gapt.LanguageProcessor.Directions(LanguageProcesso r.java:269)
    The call to the Scanner's next() method on line 269 threw that error. See the API doc for the next() method for the reasons that exception is thrown.

    The Scanner class has a method: hasNext() that can be used to test if there is more input to be read.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    EBamber is offline Member
    Join Date
    Apr 2014
    Posts
    30
    Rep Power
    0

    Default Re: Exception in thread "main" java.util.NoSuchElementException

    it's meant to be thrown if there are no other tokens to be read, but my input stream is the system, doesn't that mean that the user is supposed to enter the next token?

  4. #4
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    1

    Default Re: Exception in thread "main" java.util.NoSuchElementException

    Hi,

    The problem occurs because you close the scanner instance and this also closes the underlying stream. So your System.in stream is closed.

    Just test it yourself with simple code:
    Java Code:
    import java.util.Scanner;
    
    public class JavaTests {
    
    	public static void main(String[] args) {
    		try (Scanner scanner = new Scanner(System.in))
    		{
    			String line = scanner.next();
    		}
    		try (Scanner scanner = new Scanner(System.in))
    		{
    			String line = scanner.next();
    		}
    		
    	}
    }
    So the core thing to do here is: Do not dispose/close the scanner object (So remove the try around it).

    With kind regards,

    Konrad
    gimbal2 likes this.

  5. #5
    EBamber is offline Member
    Join Date
    Apr 2014
    Posts
    30
    Rep Power
    0

    Default Re: Exception in thread "main" java.util.NoSuchElementException

    Thanks Konrad, that did it :)
    How do I mark the thread as solved?

  6. #6
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,030
    Rep Power
    6

    Default Re: Exception in thread "main" java.util.NoSuchElementException

    O now I see, its a try-with-resources. Jebus that's hard to spot.

    I just can't believe that the System.in can actually be closed though. You learn something new every day.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  7. #7
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,424
    Rep Power
    25

    Default Re: Exception in thread "main" java.util.NoSuchElementException

    Jebus that's hard to spot.
    All these things that the compiler does "for us" make it harder to see what is happening.
    My terminology for this kind of hidden code is it is something the compiler does "to us".
    If you don't understand my response, don't ignore it, ask a question.

  8. #8
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,030
    Rep Power
    6

    Default Re: Exception in thread "main" java.util.NoSuchElementException

    Agreed, but that just marks our age ;)
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  9. #9
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default Re: Exception in thread "main" java.util.NoSuchElementException

    Quote Originally Posted by gimbal2 View Post
    Agreed, but that just marks our age ;)
    And here was me thinking auto-wrapping primitives was a pain...:)
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  10. #10
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,030
    Rep Power
    6

    Default Re: Exception in thread "main" java.util.NoSuchElementException

    Quote Originally Posted by Tolls View Post
    And here was me thinking auto-wrapping primitives was a pain...:)
    Autoboxing is a feature requested by the devil himself.

    *shakes walking stick at newfangled language features*
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  11. #11
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,424
    Rep Power
    25

    Default Re: Exception in thread "main" java.util.NoSuchElementException

    Agreed, but that just marks our age ;)
    Right, I learned programming 20+ years ago and I want them to stop changing it and confusing me.

    And now we've got lambdas to fight our way through.
    Last edited by Norm; 04-17-2014 at 05:21 PM.
    If you don't understand my response, don't ignore it, ask a question.

  12. #12
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,528
    Blog Entries
    7
    Rep Power
    20

    Default Re: Exception in thread "main" java.util.NoSuchElementException

    Lambda expressions are a litmus test: if you don't understand them, you're really old or not even potty trained ;-)

    kindest regards,

    Jos (<--- loves closures)
    cenosillicaphobia: the fear for an empty beer glass

  13. #13
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,030
    Rep Power
    6

    Default Re: Exception in thread "main" java.util.NoSuchElementException

    Hey, they're optional. Let them youngun's have fun with them, I'll just write a few keystrokes extra and keep my code easy to interpret upon a quick scan.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

Similar Threads

  1. Replies: 1
    Last Post: 11-02-2012, 11:38 PM
  2. Replies: 11
    Last Post: 09-04-2012, 04:33 AM
  3. Replies: 4
    Last Post: 05-07-2010, 07:58 PM
  4. Replies: 4
    Last Post: 06-08-2008, 02:19 PM
  5. Replies: 5
    Last Post: 05-14-2008, 01:43 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •