我试图获取用户输入的字符串的字数,但我一直得到" 0"回来了。我无法弄清楚该怎么做。
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner reader=new Scanner(System.in);
ArrayList<String> A=new ArrayList<String>();
System.out.print("Enter a sentence: ");
String a=reader.next();
int charCount=a.length();
int space;
int period;
int wordCount=0;
//word count\
for (int i=0; i<1; i++){
space=a.indexOf(" ");
if (a.charAt(0)!=' '){
if (space!=-1){
A.add(i, a.substring(0, space-1));
a=a.substring(a.indexOf(" ")+1, charCount-1);
}
if (space==-1&&a.charAt(charCount-1)=='.'){
period=a.indexOf(".");
A.add(i, a.substring(0, period));
}
charCount=a.length();
}
wordCount=A.size();
}
System.out.print("Word Count: "+A.size());
}
答案 0 :(得分:1)
为什么不尝试这样 -
public static void main (String[] args) {
Scanner reader=new Scanner(System.in);
System.out.println("Enter a sentence: ");
String str1 = reader.nextLine();
String[] wordArray = str1.trim().split("\\s+");
int wordCount = wordArray.length;
System.out.println("Word count is = " + wordCount);
}