A Java program on CodeEval had to accept a file path as an argument. I used a command line argument to do this, but I get an exception as below when I submitted my code on CodeEval. What are some potential solutions to this problem?
-
Exception in thread "main" java.util.NoSuchElementException at java.util.StringTokenizer.nextToken(StringTokenizer.java:349) at java.util.StringTokenizer.nextElement(StringTokenizer.java:407) at Main.FileRead(Main.java:61) at Main.main(Main.java:26)
-
Answer:
It looks like what you're doing is calling StringTokenizer.nextElement() (which calls StringTokenizer.nextToken()) when there are no more tokens in the string you're parsing. Under those circumstances, it will throw a NoSuchElementException. The way you usually use StringTokenizer is inside a loop which guards against this condition by using the StringTokenizer.hasMoreElements() (or StringTokenizer.hasMoreTokens()) method. Thus: StringTokenizer tok = new StringTokenizer(someString); // splits on whitespace by default while (tok.hasMoreElements()) { String s = (String)(tok.nextElement()); // do something with "s" } To do this across an entire command line, you put it inside a second loop: public class CmdLineTokenizer { public static void main(String[] args) { for (int i = 0; i < args.length; i++) { StringTokenizer tok = new StringTokenizer(args[i]); while (tok.hasMoreElements()) { String s = (String)(tok.nextElement()); // do something with "s" here } } } } Try a strategy like that, and your exception should go away. Hat tip: for the A2A.
Eric Bowersox at Quora Visit the source
Related Q & A:
- Where can I find a cruise line job?Best solution by Yahoo! Answers
- How do I get my avatar to appear when I am online?Best solution by Yahoo! Answers
- Why do I get a message in German when I post on freecycle?Best solution by wiki.freecycle.org
- I downloaded a msn that i do not like, can i get my old msn back.Best solution by Yahoo! Answers
- How can I get around paying extra charges when traveling by train through Italy with a Eurail pass?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.