【问题标题】:How to compute the frequency of occurrence of '+' and '++' in Java?如何计算Java中'+'和'++'的出现频率?
【发布时间】:2020-07-21 15:56:06
【问题描述】:

我想计算输入文本文件中所有运算符出现的频率。该文件包含运算符+++。我如何区分它们各自的频率,因为我的程序将 ++ 视为 2 个不同的 + 运算符而不是 1 个 ++

这是我的代码(input7.txt 是一个测试文件):

public static void main(String[] args) throws IOException {

    String string = new String(Files.readAllBytes(Paths.get("input7.txt"))); //String to be counted 

    int frequencyArray[] = new int[string.length()]; 
    int frequencyArray2[] = new int[string.length()];

    char stringArray[] = string.toCharArray(); //Array of characters
    int i, j;

    //Count characters

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

        frequencyArray[i] = 1;
        //frequencyArray2[i] = 1;

        for(j = i + 1; j < string.length(); j++) 
        {
            if(stringArray[i] == stringArray[j]) 
            {

                frequencyArray[i]++;    
                stringArray[j] = '0'; //To avoid revisiting a character

            }   
        }   
    }


    //Display results

    System.out.println("Characters and their corresponding frequencies");

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

        if (stringArray[i] != ' ' && stringArray[i] != '0') {

            System.out.println(stringArray[i] +"-" + frequencyArray[i]); 

        }
    }
}

【问题讨论】:

  • 请在此处分享您的代码
  • 运营商有多少?什么样的语法?
  • @TrushitShekhda 我已经添加了我的代码,谢谢。
  • @ElliottFrisch 算术、增量、关系、逻辑、按位和赋值运算符。
  • @Milan 你熟悉Arthur C. Clarke's Quarantine吗?它非常(也只涉及六个运算符)。

标签: java operators frequency


【解决方案1】:

这对我有用:

  String s = "sdfasd++ sdfadsf+asdf sdf++sadfasdf++sadfsdf+asdfasdf++";
            // create Set with all distinct characters 
Set<Character> chars = new HashSet<Character>();
            for (int i = 0; i < s.length(); i++) {
              chars.add(s.charAt(i));
            }
// count distinct characters and put Results in HashMap
            Map<Character, Integer> counts = new HashMap<Character, Integer>();
            for (Character c : chars) {
              int count = 0;
              for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) == c)
                  count++;
              }
              counts.put(c, count);
            }
// Count double-Character-Operators like this
            int countPlusPlus = 0;
            for (int i = 0; i < s.length() - 1; i++) {
              if (s.substring(i, i + 2).equals("++"))
                countPlusPlus++;
            }
        // Calculate totals like this
            int singleplusTotal = counts.get('+');
            System.out.println("Single Plus total" + singleplusTotal);
            System.out.println("Double Plus total" + countPlusPlus);
            System.out.println("Only single Plus" + (singleplusTotal - countPlusPlus * 2));

【讨论】:

  • 这不是一种有效的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-08
  • 2011-05-26
  • 1970-01-01
  • 1970-01-01
  • 2017-08-11
相关资源
最近更新 更多