试图在 java 中打印出数组

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++){
   System.out.println(elems[i]);
}

我正在尝试打印数组 elems[] 但它不起作用错误 java.util.NoSuchElementException at java.util.StringTokenizer.nextToken(StringTokenizer.java:349 似乎在行:

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

你能帮我找出并理解问题吗?

正确版本:

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

你犯的错误是 e.length() returns string 的大小(它的字符数)所以你最终调用 st.nextToken() 的次数比那里多是由 "," 分隔的实际标记。因此例外。

@Jean 发布了您正在尝试的精简版,但最终有助于理解错误

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 

现在如果你这样称呼它

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

因为你试图调用不存在的nextToken()

文档:

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

要解决您的问题,请使用 countTokens()

的长度

while(st.hasMoreElements()){
  elems[i] = st.nextToken().toString();
}

另一种选择。

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

    System.out.print(Arrays.toString(elems ));