7Kei 7Kei - 2 months ago 9x
Java Question

trying to print out the array in java

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++){

I am trying to print out the array
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?


A correct version:

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

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.