gpt4 book ai didi

java - 消失的 Arraylist 值

转载 作者:行者123 更新时间:2023-11-29 07:46:25 25 4
gpt4 key购买 nike

我正在编写一个 Java 程序,它将一个句子(或短语)翻译成计算机可以轻松读取的一组对象。想做一个简单的分词程序,以后再扩展。

我的代码是这样的:

package Literary;

import java.util.ArrayList;

public class WordParser {

public static String[] getWords(String tempone){
ArrayList<String> temptwo = new ArrayList();
ArrayList<Character> tempthree = new ArrayList();
for (int tempfour = 0; tempfour == tempone.length() - 1; tempfour++){
if (tempone.charAt(tempfour) != ' '){
tempthree.add(tempone.charAt(tempfour));
} else {
temptwo.add(getStringRepresentation(tempthree));
tempthree.clear();
}
}
String[] tempfive = new String[temptwo.size()];
for (int tempfour = 0; tempfour == tempfive.length - 1; tempfour++){
tempfive[tempfour] = temptwo.get(tempfour);
}
return tempfive;
}

/** Courtesy of Vineet Reynolds on StackExchange.
*
* "You can iterate through the list and create the string."
*
* @param list
* @return
*/

public static String getStringRepresentation(ArrayList<Character> list){
StringBuilder builder = new StringBuilder(list.size());
for(int i = 0; i == list.size() + 1; i++)
{
builder.append(list.get(i).charValue());
}
return builder.toString();
}
}

它应该接收一个字符串作为输入,并返回一个由空格分隔的字符串列表。

但是当我运行主类时:

import Literary.WordParser;

public class Start {

public static void main(String[] args) {
String x = "There was once a sword in the stone";
String[] tempstring = WordParser.getWords(x);
for (int i = 1; i == tempstring.length; i++){
System.out.println("Word " + i + " : " + tempstring[i]);
}
}
}

除了 run:BUILD SUCCESSFUL(总时间:1 秒) 外,控制台什么也没告诉我。

如果有帮助,我正在使用 Netbeans 8 和 Java 1.7。

最佳答案

看起来问题出在这里:

for (int i = 1; i == tempstring.length; i++) {

这个 for 循环最多运行一次:if tempstring正好是一个String long,它应该打印出这个词。

但是,由于您的测试句子有 8 个单词,因此不会打印出任何内容(前提是 WordParser 工作正常)。

您可能想将此行更改为:(注意 <i 之间的 tempstring.length。)

for (int i = 1; i < tempstring.length; i++) {

这样它将遍历 tempstring 中的所有项目.

关于java - 消失的 Arraylist 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25234032/

25 4 0