首页 > 解决方案 > 计算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 是单词意味着两个字符存在。请我不想使用拆分功能。

标签: java

解决方案


你可以这样做:

1)制作一个变量,在你面对一个数字时会被激活

boolean confront_number = false;

2)在你的循环中,如果你一直面对一个数字(不是一个带数字的单词):那么这将是真的

3)最后,根据您的情况,只有当该变量为假时,您才必须递增

if(Character.isWhitespace(ch) && confront_number==false)
    W++;

推荐阅读