【问题标题】:Take a quote, and show how many characters, words, and average of each word引用,并显示每个单词的字符数、单词数和平均值
【发布时间】:2017-12-05 00:07:02
【问题描述】:

我对Java有点陌生,请不要告诉我使用方法等,因为我不知道该怎么做。但我确实知道一些 charAt 的东西,所以任何人都可以帮我找到单词的数量,以及每个单词的平均值,我做了第一部分。这是我的代码。

import java.util.Scanner;
public class FavouriteQuote {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String sQuote;
        int counter = 0;

        Scanner input = new Scanner (System.in);
        System.out.print("Enter one of your favourite quotes: ");
        sQuote = input.nextLine();
        input.close();

        for (int i = 0; i < sQuote.length(); i ++) {
            counter ++;
        }
        System.out.println(counter);
    }

}

【问题讨论】:

  • 也许 string 类的 split() 方法将有助于查找单词和 hashmap 用于单词计数。但是,我对每个单词的平均值感到困惑,因为您只要求用户输入一次然后退出,因此您的单词平均值将只是它们的字数
  • 如果您是新手,那么阅读文档真的很有帮助。 String 类有你需要的……docs.oracle.com/javase/7/docs/api/java/lang/String.html
  • @RAZ_Muh_Taz 如果 OP 知道他只处理 ASCII 字母,那么整数数组比 HashMap 更容易处理。但我同意 Map 将是用于更大的 CharSet 的正确方法
  • 每个单词的平均值,如???

标签: java char


【解决方案1】:

但是你需要多少平均值?报价中的平均字长? 那么您的代码可能如下所示:

    ...
    input.close();

    System.out.println("Characters in quote:" + sQuote.length());

    String[] words = sQuote.split("\\s");
    // or 
    // String[] words = sQuote.split(" ");

    System.out.println("words in quote:" + words.length);

    int totalWordsLength =0;
    for (String word: words) 
    {
        totalWordsLength = totalWordsLength + word.length();
    }
//or with loop counter
//      for (int i=0; i < words.length; i++) 
//      {
//          totalWordsLength += words[i].length();
//      }       

    System.out.println("average word length in quote:" + (totalWordsLength/ words.length));

记住:这里的平均值是int,所以它只是除法结果的整数部分。即 11/3 = 3 顺便说一句(除了问题) - 你不需要你的 for 循环。这没有任何意义。 counter = sQuote.length() 也一样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-15
    • 2013-03-11
    • 1970-01-01
    • 1970-01-01
    • 2014-04-16
    • 2019-02-01
    • 1970-01-01
    相关资源
    最近更新 更多