首页 文章

使用方法计算字符串中的单词

提问于
浏览
0

我有一个项目来创建一个程序,它接受一个字符串作为输入,然后打印字符串中的单词数作为输出 . 我们应该使用3种方法,一种用于读取输入,一种用于打印输出,另一种用于计算单词 .

我知道我遗漏了一些基本的东西,但我已经花了几个小时在这上面,无法弄清楚为什么程序不会运行它应该 . 我需要保持程序非常简单,所以我不想编辑太多,只是找到问题并修复它,以便它将正确运行 .

示例:输入一串文字:快速的棕色狐狸跳过懒狗 . 9个字

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter text: ");
    String words = wordInput(in);
    int count = wordCount(words);
    System.out.println(words);
    System.out.println(count);
    printLine(count);
}

private static String wordInput(Scanner in)
{
    String words = in.nextLine();
    return words;
}
private static int wordCount(String words)
{
    int length = words.length();
    int ctr = 0;
    int spot = 0;
    int stop = 1;
    char space = ' ';
    char end = '.';
    char com = ',';
    char yes = '!';
    char question = '?';

    while (length > 0 && stop > 0)
    {
        if (words.charAt(spot) == space)
        {
            ctr++;
            spot++;
        }
        else if (words.charAt(spot) == com)
        {
            spot++;
        }
        else if (words.charAt(spot) == yes || words.charAt(spot) == end || words.charAt(spot) == question)
        {
            stop = -1;
        }
        else if (spot > length)
        {
            stop = -1;
        }
        else
            spot++;
    }
    return ctr + 1;
}
private static void printLine(int ctr)
{
    System.out.println(ctr + " words");
}

2 回答

  • 0

    假设输入字符串的人不会出现语法错误,请尝试在所有空格中拆分字符串并将其设置为等于字符串[] . 这是一个例子:

    String temp = JOptionPane.showInputDialog(null, "Enter some text here");
        String[] words = temp.split(" ");
        JOptionPane.showMessage(null, String.format("Words used %d", words.length));
    
  • 0

    这是一个重写的 wordCount ,可以按照您的要求执行,对代码进行最少的更改 . 但是,我不确定它会产生你期望的答案 .

    private static int wordCount(String words)
    {
        int length = words.length();
        int ctr = 0;
        int spot = 0;
        char space = ' ';
        char end = '.';
        char com = ',';
        char yes = '!';
        char question = '?';
    
        while (spot < length)
        {
            if (words.charAt(spot) == space)
            {
                ctr++;
                spot++;
            }
            else if (words.charAt(spot) == com)
            {
                spot++;
            }
            else if (words.charAt(spot) == yes || words.charAt(spot) == end || words.charAt(spot) == question)
            {
                break;
            }
            else
                spot++;
        }
        return ctr + 1;
    }
    

    但是,从根本上说,你正在尝试计算字符串中的单词,这是一种已知的艺术 . 一些选项和进一步阅读:

    这导致更简单的结果:

    private static int wordCount(String words) {
        return words.split("\\s+").length;
    }
    

相关问题