-3
System.out.println("Please input the elements and seperate each by a  comma.");
e = dk.nextLine();
String[] elems = new String[e.length()];
st = new StringTokenizer(e,",");

for (int i = 0; i<e.length(); i++) {
   elems[i] = st.nextToken().toString();
}

for (int i=0; i<e.length(); i++){
   System.out.println(elems[i]);
}

I am trying to print out the array elems[] but it wont work the error java.util.NoSuchElementException at java.util.StringTokenizer.nextToken(StringTokenizer.java:349 seems to be at line:

elems[i] = st.nextToken().toString();

can you help me identify and understand the problem?

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
7Kei
  • 25
  • 1
  • 1
    And this error is...? – Marc B Jul 25 '16 at 15:44
  • Did you get something like `java.lang.FooException at foo.bar.baz() at bar.foobar() at foo.bar.qux()`? – The SE I loved is dead Jul 25 '16 at 15:47
  • For starters, initialize the array (`elems`) with `st.countTokens()` instead of `e.length()`. `st.nextToken().toString()` is redundant, use `st.nextToken()` instead. The loops also have to be changed accordingly. – boxed__l Jul 25 '16 at 15:50
  • The error is Exception in thread "main" java.util.NoSuchElementException at java.util.StringTokenizer.nextToken(StringTokenizer.java:349) @MarcB @ dorukayhan – 7Kei Jul 25 '16 at 15:51
  • The problem is that there are fewer tokens in `e` than the length of `e`: think about `"Hello,World"`: 2 tokens (`Hello` and `World`), but the length is 11. You run out of things to read. – Andy Turner Jul 25 '16 at 15:54
  • @AndyTurner thanks for the explanation – 7Kei Jul 25 '16 at 16:00

3 Answers3

4

A correct version:

String[] elems = e.split(",");
for(String elem : elems) {
    System.out.println(elem);
}

The mistake you made is that e.length() returns the size of the string (its number of characters) so you ended up calling st.nextToken() more times than there are actual tokens separated by ",". Hence the exception.

Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
0

@Jean posted a slim version of what you are trying, but ultimately to help to understand the error

e = dk.nextLine(); // input: Alfredo,Bauer,Cisco
String[] elems = new String[e.length()]; // length is 20 
st = new StringTokenizer(e,","); // st has a length of 3 

Now if you call it like this

for(int i = 0;i<e.length();i++){
elems[i] = st.nextToken().toString(); // NoSuchElementException
}

Because you try to call the nextToken() which does not exist.

The docs:

Returns the next token from this string tokenizer.
Throws: NoSuchElementException - if there are no more tokens in this tokenizer's string.

To fix your problem use the length of countTokens()

OR

while(st.hasMoreElements()){
  elems[i] = st.nextToken().toString();
}
Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
0

Another alternative.

    String[] elems = e.split(",");

    System.out.print(Arrays.toString(elems ));
AchillesVan
  • 4,156
  • 3
  • 35
  • 47