java - 计算java中的单词数
问题描述
Scanner sc=new Scanner(System.in);
char ch;
int W=0;
String s;
System.out.println("enter a String:");
s = sc.nextLine();
for(int i = 0;i<s.length();i++)
{
ch = s.charAt(i);
if(Character.isWhitespace(ch))
W++;
}
System.out.println(W+1);
}
}
when i am executing above program with the
input :COMPUTER APPLICATION
its giving correct output no of words 2
in case if i entered
input: COMPUTER APPLICATION 1
answer should be for the no of words 2 but answer is displaying 3 program code also counts last 1.
据我所知1不是单词,单词意味着一组字符答案应该是2。1不应该被计算。采用其他输入输入:计算机应用程序 12 现在对于单词 3 的频率的上述输入答案很好,因为最后一个单词 12 是单词意味着两个字符存在。请我不想使用拆分功能。
解决方案
你可以这样做:
1)制作一个变量,在你面对一个数字时会被激活
boolean confront_number = false;
2)在你的循环中,如果你一直面对一个数字(不是一个带数字的单词):那么这将是真的
3)最后,根据您的情况,只有当该变量为假时,您才必须递增
if(Character.isWhitespace(ch) && confront_number==false)
W++;
推荐阅读
- javascript - Messenger Input 在 react-native 中展开动画
- android - 如何将 Webrtc 的相机输出流式传输到本机 android 上的 Wikiitude sdk
- azure-application-insights - 来自应用程序洞察的请求数据返回 null
- prometheus - 当 Prometheus 宕机时,Prometheus 客户端库的行为如何?
- c++ - 自动扣除和模板类型扣除有什么区别?
- python - 如何在 Python 的给定函数的特定参数上设置无限迭代?
- java - 如何启用 Tomcat 的 JMX Catalina 支持?
- android - build.gradle:如何解决“无法解决依赖关系”错误?
- html - html5画布上下文在整页中模糊
- c++ - 如何在 C++ 中应用对字符串变量进行计数的概念