首页 > 解决方案 > 如何在java中按初始字符计算平均词条长度?

问题描述

我有一个文件(txt),其中包含一段文本,我必须通过 java 中的初始字符计算平均术语长度。例如,如果有 4 个单词“purple, brown, pink, black”,输出应该是;p = 5 b = 5

我想了好几个小时,但我做不到我能做的只是拆分单词。我不知道如何制作具有相同初始字符的单词列表。

try(Scanner scanner = new Scanner(new FileReader("sampleText.txt"))) {

            ArrayList<String> arrlist = new ArrayList<String>();

            while (scanner.hasNext()) {

                String sampleText = scanner.nextLine();

                String[] array = sampleText.split(" ");

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

                    if (array[i].charAt(0) = Integer ) //tried to not take numbers didn't work

                    System.out.println(array[i]);

                    arrlist.add(array[i]);
                }

                System.out.print(array);

                break;

            }

        }

        catch (FileNotFoundException e) {
            System.out.println("FNF Exception");
        }
        catch (ArrayIndexOutOfBoundsException a) {
            System.out.println("AIOoB Exception");
        }

    }

标签: java

解决方案


您可以通过以下方式解决它:

  1. 用逗号分割字符串,后跟空格(即,\\s+),将生成的字符串存储到 aList<String>中,然后对列表进行排序。
  2. 使用 aMap<Character, Double>存储计算的数据,其中键是初始字符,值是平均术语长度。
  3. 使用变量来计算总和并对元素进行计数,以便计算平均值。使用内部循环,浏览列表,直到获得具有不同首字母的元素。
  4. 一旦你得到一个具有不同首字母的元素,就终止内部循环。此时,将带有平均值的首字母存储到地图中。

演示:

import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        String str = "purple, brown, pink, black";

        // Split the string and store into a List<String>
        List<String> list = Arrays.asList(str.split(",\\s+"));

        // Sort the list
        list.sort(Comparator.naturalOrder());

        // Use a Map<String, Integer> to store the data
        Map<Character, Double> map = new LinkedHashMap<>();

        for (int i = 0; i < list.size(); i++) {
            // Get the element and move to the loop counter to the next index
            String element = list.get(i++);

            double sum = element.length();
            Character ch = Character.valueOf(element.charAt(0));
            int count = 1;

            // Starting with the next index, iterate the list until you find an element with
            // a different initial letter
            while (i < list.size() && ch.equals(Character.valueOf(list.get(i).charAt(0)))) {
                // Add the length of element and move the outer loop counter to the next index
                sum += list.get(i++).length();
                count++;
            }

            map.put(ch, sum / count);

            // Adjust the the outer loop counter by decrementing by 1
            i--;
        }

        // Display the result
        System.out.println(map);
    }
}

输出:

{b=5.0, p=5.0}

推荐阅读