java - 索引无法正确读取

标签 java arrays indices

该代码正在剪切,在第一个数组位置 (0) 中添加一个空格,并在第二个位置 (1) 上开始单词。因此,单词的最后一个字母会被删除,因为数组的长度是由单词长度本身决定的。

输入单词是“hummus”,但输出是“hummu”(注意前导空格)。

我的代码(一些变量在上面的不同代码部分中声明):

//Reads in the wordlist
for (int x = 0; x < wordList.length; x++) {
    word = wordList[x];
}

//Splits the word chosen from word list into an array
JTextField[] wordAmount = new JTextField[word.length()];//Creates a JtextField for each letter
String[] letters = word.split("");
String temp;
int wordLength = word.length();

//Determines amount of textfields are needed for the word
for (int j = 0; j < wordLength; j ++) {
    temp = letters[j];
    wordAmount[j] = new JTextField();
    wordAmount[j].setText(temp);
    System.out.println(wordAmount[j].getText());
}## Heading ##

最佳答案

使用调试器应该很容易单步执行。我当前使用的计算机上没有设置 Java,但我很确定您的问题出在这一行:

String[] letters = word.split("");

我认为这会在两端产生多余的空间。

这是一种将字符串拆分为字母的非常奇怪的方法;为什么不直接使用 toCharArray 并将每个 char 转换为 String

<小时/>

顺便说一句,您到底期望什么

for (int x = 0; x < wordList.length; x++) {
    word = wordList[x];
}

做什么?

关于java - 索引无法正确读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30672104/

相关文章:

python - "invert"一个数组,即将 2d 索引列表转换为 1d 索引的 2d 数组

java - Eclipse 中的奇怪 “java.lang.NoClassDefFoundError”

java - JMenuBar 导致内容 Pane 重新绘制不正确

java - IOException : Could not initialize SSL context - Apache Commons Net - Android

c - C中的动态数组实现

mysql - MySQL 数据库上的位图索引

python - 对给定列表 Python 的给定范围内的所有数字求和

java - 泛型代码删除不起作用

javascript - 如何在javascript中分离一个json数据

php - 了解数组符号(特别是 mysql_fetch_array 和 print_r)