gpt4 book ai didi

java - ArrayList不添加字符串

转载 作者:行者123 更新时间:2023-11-30 06:52:07 25 4
gpt4 key购买 nike

我试图获取用户输入的字符串的字数,但结果总是返回“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());
}

最佳答案

你为什么不尝试这样-

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);
}

关于java - ArrayList不添加字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42545828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com