Note that there are some explanatory texts on larger screens.

plurals
  1. POGetting relative frequency of each character in a string in java
    primarykey
    data
    text
    <p>I wanted to get the average of each unique character in a string. I have an example here as it would be easier to illustrate it.</p> <p>String: </p> <pre><code>The big brown fox </code></pre> <p>Average of each character including spaces:</p> <pre><code>T = 1/17 = .058 h = 1/17 = .058 e = 1/17 = .058 ' '= 3/17 = .176 b = 2/17 = .117 i = 1/17 = .058 g = 1/17 = .058 r = 1/17 = .058 o = 2/17 = .117 w = 1/17 = .058 n = 1/17 = .058 f = 1/17 = .058 x = 1/17 = .058 </code></pre> <p>So far all my attempts have failed, think my brain is not working at the moment. How do I code this? Any help or input will be greatly appreciated. </p> <p>I have this code as a solution. It just came to me when I was copy pasting my code here in stack. I hope this is not a re-post because I just answered the same thing a few minutes ago but it didn't show up.</p> <pre><code> Map&lt;String, Integer&gt; storeCharCount = new HashMap&lt;String, Integer&gt;(); String a = "The big brown fox"; for (int x=0; x&lt;a.length(); x++){ char getChar = a.charAt(x); String convGetChar = Character.toString(getChar); Integer countChar = storeCharCount.get(convGetChar); storeCharCount.put(convGetChar, (countChar==null?countChar=1:countChar+1)); } System.out.println("Map: "+ storeCharCount); double RelFrequency = 0; for (Map.Entry&lt;String, Integer&gt; getValue: storeCharCount.entrySet()){ RelFrequency = (double)(getValue.getValue())/(a.length()); System.out.println("Character "+getValue.getKey() +" Relative Frequency: "+RelFrequency); } </code></pre> <p>Here is the output</p> <pre><code>Map: {f=1, g=1, =3, e=1, b=2, n=1, o=2, h=1, i=1, w=1, T=1, r=1, x=1} Character f Relative Frequency: 0.058823529411764705 Character g Relative Frequency: 0.058823529411764705 Character Relative Frequency: 0.17647058823529413 Character e Relative Frequency: 0.058823529411764705 Character b Relative Frequency: 0.11764705882352941 Character n Relative Frequency: 0.058823529411764705 Character o Relative Frequency: 0.11764705882352941 Character h Relative Frequency: 0.058823529411764705 Character i Relative Frequency: 0.058823529411764705 Character w Relative Frequency: 0.058823529411764705 Character T Relative Frequency: 0.058823529411764705 Character r Relative Frequency: 0.058823529411764705 Character x Relative Frequency: 0.058823529411764705 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload