gpt4 book ai didi

java - 如何将 StringTokenizer 结果带到 Java 中的 ArrayList?

转载 作者:行者123 更新时间:2023-11-29 06:54:41 26 4
gpt4 key购买 nike

我想将 StringTokenizer 结果带到 ArrayList。我使用了以下代码,并在第一个打印语句中 stok.nextToken() 打印了正确的值。但是,在 ArrayList 的第二个打印语句中给出错误 java.util.NoSuchElementException 。我如何将这些结果放入 ArrayList?

 import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class Test {
public static void main(String[] args) throws java.io.IOException {

ArrayList<String> myArray = new ArrayList<String>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter : ");
String s = br.readLine();
StringTokenizer stok = new StringTokenizer(s, "><");
while (stok.hasMoreTokens())
System.out.println(stok.nextToken());
// -------until now ok

myArray.add(stok.nextToken()); //------------???????????
System.out.println(myArray);

}
}

最佳答案

引用 StringTokenizer 的 javadoc :

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

“新代码”是指为 Java 1.4 或更高版本编写的任何代码,即远古时代。


while 循环将从分词器中提取所有值。当您随后调用 nextToken() after 已经提取了所有标记时,为什么您对出现异常感到惊讶?

特别是 nextToken() 的 javadoc 中的这段引述:

Throws NoSuchElementException if there are no more tokens in this tokenizer's string.

您可能是故意这样做的吗?

ArrayList<String> myArray = new ArrayList<>();
StringTokenizer stok = new StringTokenizer(s, "><");
while (stok.hasMoreTokens()) {
String token = stok.nextToken(); // get and save in variable so it can be used more than once
System.out.println(token); // print already extracted value
// more code here if needed
myArray.add(token); // use already extracted value
}
System.out.println(myArray); // prints list

关于java - 如何将 StringTokenizer 结果带到 Java 中的 ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36894895/

26 4 0