gpt4 book ai didi

java - 计算字符串中的单词数并从方法中调用它?

转载 作者:行者123 更新时间:2023-12-01 06:42:31 25 4
gpt4 key购买 nike

这是我到目前为止的代码,我想做的是调用我创建的方法来向用户显示用户输入中有多少个单词。我不确定我所调用的电话是错误的还是什么,但我是否可以从知道自己在做什么的人那里得到一些帮助。

import java.util.Scanner;

public class Chapter3Question5 {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);

System.out.println("Type some words: ");
String s = in.nextLine();
System.out.println("There are " + (countWords) + " words.");
//want to call the method here and print the results

in.close();
}

public static int countWords(String str) {
int wordCount = 0;

boolean word = false;
int endLine = str.length() - 1;

for (int i = 0; i < str.length(); i++) {

if (Character.isLetter(str.charAt(i)) && i != endLine) {
word = true;
} else if (!Character.isLetter(str.charAt(i)) && word) {
wordCount++;
word = false;
} else if (Character.isLetter(str.charAt(i)) && i == endLine) {
wordCount++;
}
}
return wordCount;
}
}

最佳答案

您需要根据您的情况通过其名称和良好的参数来调用您的方法:

String s = in.nextLine();
System.out.println("There are " + countWords(s) + " words.");

一方面,你的方法很好,而且很有效

<小时/>

提示(只是为了让您知道另一种方式)这会做同样的事情:

public static int countWords(String str) {
return str.split("\\s+").length;
}

它将在有空格的地方分割你的句子并创建一个数组(单词数组)并获取它的长度:单词数

关于java - 计算字符串中的单词数并从方法中调用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46553133/

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