所以这个程序应该做的是,用户输入一个字符串,程序将检查charAt(0)到charAt(字符串长度为1)的每个字符,它将检查它是否是一个有效的字母(AZ或az) . 任何非字母都被视为单词分隔符 .
每当下一个字符为字母时,计数器将递增 . 一旦字符无效(数字,符号,标点,空格等),计数器将重置为0,并且无效字符前的字符到最后一个有效字符(在这种情况下,charAt(0)让我们说)将创建单词1 . 如果字符无效,它会将计数器分配给最初以索引0开头的数组,然后将增加索引,以便将其分配给下一个字长 .
如何根据此程序中创建的单词数创建数组?例如,如果我输入以下字符串,则数组的长度为7 .
8这个pro98gram doin8g是什么? Word1 = What,Word2 = is,Word3 = this,Word4 = pro,word5 = gram,word6 = doin,word7 = g .
另外,每次进入程序中的else语句时,如何为特定的数组索引分配一个数字值,例如word [a],其中a为0,1,2,3,4等 .
这就是我到目前为止所做的 .
import java.util.Scanner;
public class WordCountInString {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a = 0; // Initial index is 0;
int[] word = new int[a]; // Creating an array.
String string;
System.out.print("Enter a String of Data Please: ");
string = input.nextLine();
int counter = 0;
for (int i = 0; i < string.length(); i++) {
if (string.charAt(i) >= 'a' && string.charAt(i) >= 'z' // Check to see if charAt(i) is a letter.
|| string.charAt(i) >= 'A' && string.charAt(i) <= 'Z') {
counter++; // Counter every time the next char is a letter.
}
else {
word[a] = counter; // Assign the array of index(a) to counter
a++; // Go to the next index.
counter = 0; // Reset the counter to create a new word.
}
}
for (int j = 0; j < word.length; j++) { //Prints out all the arrays.
System.out.println(word[j]); // Print the value of each array.
}
}
}
1 回答
从代码判断,你得到的错误是当你试图用a增加a时 .
但是,您永远不会调整阵列的大小 . 您不能简单地增加数组索引的值 . 这将在数组中查找尚不存在的索引 .
我把这个 Build 在你的代码上 . 您需要查看代码末尾的两个函数; addToArray和resizeArray .
这些工作负责将新计数添加到数组中,并将数组大小调整为大小 .
更优雅的方法是使用列表,因为您只需添加下一个计数而无需知道最终大小 . 要阅读有关列表的更多信息,请查看JavaDocs或TutorialsPoint上的一个好例子 .