【发布时间】:2016-11-28 05:35:18
【问题描述】:
所以这个程序应该做的是,用户输入一个字符串,程序会检查每个字符从 charAt(0) 到 charAt(length of string - 1) 它会检查它是否是一个有效的字母(A-Z 或 a-z)。任何非字母都被视为单词分隔符。
每当下一个字符是字母时,计数器就会增加。一旦字符无效(数字、符号、标点符号、空格等),计数器将重置为 0,并且在无效字符之前的字符到最后一个有效字符(在这种情况下为 charAt(0) 假设)将创建单词 1。当该字符无效,它会将计数器分配给最初从索引 0 开始的数组,然后将增加索引以便可以将其分配给下一个字长。
如何根据该程序中创建的单词数创建一个数组?例如,如果我输入以下字符串,则数组的长度为 7。
8this pro98gram 是做什么的?
Word1= 什么,Word2= 是,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.
}
}
}
【问题讨论】:
-
很可能你必须遍历字符串两次——第一次你会确定有多少单词。你可以通过计算非字母的数量来做到这一点。那么如果
n是字数的话,可以根据需要创建new int[n]或者new String[n]。如果允许您使用ArrayList,那会更好,因为您不需要事先知道它有多大。但如果你必须使用数组,这将是一种方法。 -
我还没有学过接口,所以还不会使用接口。但是我在运行程序时遇到了错误。这是为什么呢?
-
@Majestic 也许你应该告诉我们你遇到了什么错误来帮助你编写代码。
-
这是第 24 行的“java.lang.ArrayIndexOutOfBoundsException: 0”,即 else 语句中“word[a] = counter”处的行。
标签: java arrays string for-loop string-length