该代码正在剪切,在第一个数组位置 (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/