Calculate the frequency of characters in a stringReturn a string without the first two charactersCalculate all possible combinations of given charactersDelete the characters of one string from another stringBasic string compression counting repeated charactersString 'expanding' - reinserting repeating charactersWord separator and Pig Latin program - final editPerform basic string compression using the counts of repeated charactersFollow-up 2: Copy File, remove spaces in specific linesProgram to compress a string of charactersSwapping pairs of characters in a String

Have the tides ever turned twice on any open problem?

How do I use long payment IDs in CLI v0.14 / GUI v0.14?

Do native speakers use "ultima" and "proxima" frequently in spoken

How can we expose a lightning web component on a Mobile app?

What favor did Moody owe Dumbledore?

Why is the President allowed to veto a cancellation of emergency powers?

What exactly is this small puffer fish doing and how did it manage to accomplish such a feat?

PTIJ: Who should I vote for? (21st Knesset Edition)

Is it insecure to send a password in a `curl` command?

Employee lack of ownership

Is there a hypothetical scenario that would make Earth uninhabitable for humans, but not for (the majority of) other animals?

What is the relationship between relativity and the Doppler effect?

While on vacation my taxi took a longer route, possibly to scam me out of money. How can I deal with this?

How to get the n-th line after a grepped one?

How to define limit operations in general topological spaces? Are nets able to do this?

The average age of first marriage in Russia

Comment Box for Substitution Method of Integrals

How to generate binary array whose elements with values 1 are randomly drawn

Recruiter wants very extensive technical details about all of my previous work

How to terminate ping <dest> &

Difference between 戦争 and 戦火 in this exchange

Why one should not leave fingerprints on bulbs and plugs?

Is there a term for accumulated dirt on the outside of your hands and feet?

Should I use acronyms in dialogues before telling the readers what it stands for in fiction?



Calculate the frequency of characters in a string


Return a string without the first two charactersCalculate all possible combinations of given charactersDelete the characters of one string from another stringBasic string compression counting repeated charactersString 'expanding' - reinserting repeating charactersWord separator and Pig Latin program - final editPerform basic string compression using the counts of repeated charactersFollow-up 2: Copy File, remove spaces in specific linesProgram to compress a string of charactersSwapping pairs of characters in a String













6












$begingroup$


I wrote this program to check the number of times that each letter appears in a string input by the user. It works fine, but is there a more efficient or alternative solution of going about this task than reiterating through a twenty-six-element-long array for every single character?



import java.util.Scanner;
public class Letters
public static void main(String[] args)
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
char[] c = 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z';
int[] f = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;
System.out.println("Enter a string.");
String k = sc.nextLine();
String s = k.toUpperCase();
s = s.trim();
int l = s.length();
System.out.println("Checking string = " + s);
char ch;
for (int i = 0; i < l; i++)
ch = s.charAt(i);
for (int j = 0; j < c.length; j++)
if (ch == c[j])
f[j]++;



System.out.println("ChartFreq");
for (int i = 0; i < c.length; i++)
if (f[i] != 0)
System.out.println(c[i] + "t" + f[i]);













share|improve this question









New contributor




Artemis Hunter is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$











  • $begingroup$
    Hi Artemis! Welcome! This is a great question! I'm sure someone would help you with that!
    $endgroup$
    – Emma
    10 hours ago















6












$begingroup$


I wrote this program to check the number of times that each letter appears in a string input by the user. It works fine, but is there a more efficient or alternative solution of going about this task than reiterating through a twenty-six-element-long array for every single character?



import java.util.Scanner;
public class Letters
public static void main(String[] args)
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
char[] c = 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z';
int[] f = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;
System.out.println("Enter a string.");
String k = sc.nextLine();
String s = k.toUpperCase();
s = s.trim();
int l = s.length();
System.out.println("Checking string = " + s);
char ch;
for (int i = 0; i < l; i++)
ch = s.charAt(i);
for (int j = 0; j < c.length; j++)
if (ch == c[j])
f[j]++;



System.out.println("ChartFreq");
for (int i = 0; i < c.length; i++)
if (f[i] != 0)
System.out.println(c[i] + "t" + f[i]);













share|improve this question









New contributor




Artemis Hunter is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$











  • $begingroup$
    Hi Artemis! Welcome! This is a great question! I'm sure someone would help you with that!
    $endgroup$
    – Emma
    10 hours ago













6












6








6





$begingroup$


I wrote this program to check the number of times that each letter appears in a string input by the user. It works fine, but is there a more efficient or alternative solution of going about this task than reiterating through a twenty-six-element-long array for every single character?



import java.util.Scanner;
public class Letters
public static void main(String[] args)
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
char[] c = 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z';
int[] f = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;
System.out.println("Enter a string.");
String k = sc.nextLine();
String s = k.toUpperCase();
s = s.trim();
int l = s.length();
System.out.println("Checking string = " + s);
char ch;
for (int i = 0; i < l; i++)
ch = s.charAt(i);
for (int j = 0; j < c.length; j++)
if (ch == c[j])
f[j]++;



System.out.println("ChartFreq");
for (int i = 0; i < c.length; i++)
if (f[i] != 0)
System.out.println(c[i] + "t" + f[i]);













share|improve this question









New contributor




Artemis Hunter is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$




I wrote this program to check the number of times that each letter appears in a string input by the user. It works fine, but is there a more efficient or alternative solution of going about this task than reiterating through a twenty-six-element-long array for every single character?



import java.util.Scanner;
public class Letters
public static void main(String[] args)
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
char[] c = 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z';
int[] f = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;
System.out.println("Enter a string.");
String k = sc.nextLine();
String s = k.toUpperCase();
s = s.trim();
int l = s.length();
System.out.println("Checking string = " + s);
char ch;
for (int i = 0; i < l; i++)
ch = s.charAt(i);
for (int j = 0; j < c.length; j++)
if (ch == c[j])
f[j]++;



System.out.println("ChartFreq");
for (int i = 0; i < c.length; i++)
if (f[i] != 0)
System.out.println(c[i] + "t" + f[i]);










java strings






share|improve this question









New contributor




Artemis Hunter is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Artemis Hunter is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 7 hours ago







Artemis Hunter













New contributor




Artemis Hunter is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 11 hours ago









Artemis HunterArtemis Hunter

335




335




New contributor




Artemis Hunter is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Artemis Hunter is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Artemis Hunter is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











  • $begingroup$
    Hi Artemis! Welcome! This is a great question! I'm sure someone would help you with that!
    $endgroup$
    – Emma
    10 hours ago
















  • $begingroup$
    Hi Artemis! Welcome! This is a great question! I'm sure someone would help you with that!
    $endgroup$
    – Emma
    10 hours ago















$begingroup$
Hi Artemis! Welcome! This is a great question! I'm sure someone would help you with that!
$endgroup$
– Emma
10 hours ago




$begingroup$
Hi Artemis! Welcome! This is a great question! I'm sure someone would help you with that!
$endgroup$
– Emma
10 hours ago










3 Answers
3






active

oldest

votes


















3












$begingroup$

Separate logical elements



It's good to separate different logical parts of a program, for example:



  • Parse input: a function that takes an InputStream and returns a String

  • Compute frequencies: a function that takes a String and returns frequencies in some form. In your current program you used an int[], it could have been a Map<Character, Integer>.

  • Print the frequencies: a function that takes the frequencies in some form, returns nothing, and prints to screen the frequencies nicely formatted.

Computing indexes of letters



If the input string contains only uppercase letters, then you can translate those letters to array indexes in the range of 0 to 25 (inclusive) like this:



int index = ch - 'A';


This eliminates the nested loop you had.
It also eliminates the need for the c array.



Initializing arrays



Instead of this:




int[] f = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;



You could write simply int[] f = new int[26];



Instead of this:




char[] c = 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z';



I would take a lazy approach and write char[] c = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();



Use better variable names



Single-letter variable names should only be used for trivial, highly transient things.
The names f and c in the program are inappropriate, and make the program more difficult to read.






share|improve this answer









$endgroup$












  • $begingroup$
    I've been sticking to arrays because I haven't yet started learning about Maps and HashMaps. I'll be sure to check them out now... Thanks for pointing out the toCharArray() function. I was unaware that it existed.
    $endgroup$
    – Artemis Hunter
    7 hours ago










  • $begingroup$
    I didn't mean that you should use a Map. I mentioned as an option. Both ways have advantages and disadvantages, the best solution depends on the use case. Here it doesn't matter much.
    $endgroup$
    – janos
    7 hours ago










  • $begingroup$
    Understood. BTW, thought I'd point out about the variable names, I actually find it pretty convenient to go with single-letter names: c for character, f for frequency, i for iterator and so on.
    $endgroup$
    – Artemis Hunter
    6 hours ago






  • 1




    $begingroup$
    @TomG But your consumer usually wouldn't have access to your code, would they? The consumer is meant to receive the application which the code runs. In case of another coder, you might be right, but even a simple remark next to the variable's declaration might suffice, would it not? Actually, I only use single letters in my basic programs, like the one above. Usually my programs have clear names.
    $endgroup$
    – Artemis Hunter
    5 hours ago







  • 2




    $begingroup$
    @ArtemisHunter There are aspects of style that are subjective. In this example, good objective arguments exist, against comments. 1. The consumers of your binaries indeed don't care about variable names. But the consumers of your source code do: the human reviewers and maintainers. Without descriptive names, it's hard to keep in mind what f meant, you may have to scan back in the program to understand, which is a mental burden. 2. Comments can go out of sync with the code they describe. If instead of comments you write in a way that's self-descriptive, that's a better long-term solution.
    $endgroup$
    – janos
    4 hours ago


















2












$begingroup$

Warnings



Don't use the suppresswarnings annotation for things that can be fixed easily. I don't recognize the "resource" warning, I guess it's specific to the compiler you're using (Eclipse?). Probably comes from using the Scanner without closing it properly. By using the try-with-resources -statement for anything that supports java.lang.AutoCloseable, this will be handled for you automatically.



Variables and naming



There's no point in trying to save a few keystrokes by using short variable names. The compiler doesn't care what the names are, so you can just as well use human-readable names. The exception here being de-facto standardized loop indices like i and j.



Any decent code editor or IDE will autocomplete the names for you, so it's not that much more to type. A modified section of your original code, notice how I also chained the call to toUpperCase() directly after the nextLine() call. No need to create a new variable for the case-corrected string:



Scanner inputScanner = new Scanner(System.in);
String input = inputScanner.nextLine().toUpperCase();


Object methods



Familiarize yourself with the Java standard library and API. The String class has a method for returning its contents as a char array: toCharArray(). You could use that, combined with the enhanced for loop to simplify your loop:



String input = // fetch string somehow
for (char inputChar : input.toCharArray())
// Loop processing here



Printing an array is similarly a one-line operation: System.out.println(Arrays.toString(your array here))



Tips and tricks



There's a neat(?) trick for calculations using chars in Java. As you are upper-casing all the chars, you can use 'A' as the base for the array index. So instead of having two arrays, one with the frequencies, one for the char-to-index mapping, use subtraction from 'A' to get the index:



for (char inputChar : input.toCharArray()) 
frequencies[inputChar - 'A']++;



Alternative implementation



Here's my alternative implementation using only the same data structures as in your original post. I do agree with Vishal Dhanotiya about the use of a map for this.



import java.util.Arrays;
import java.util.Scanner;

public class Letters
public static void main(String[] args)

int[] frequencies = new int[26];

try (Scanner scanner = new Scanner(System.in))
System.out.print("Enter a string: ");
String input = scanner.nextLine().toUpperCase();

for (char inputChar : input.toCharArray())
frequencies[inputChar - 'A']++;


for (int i = 0; i < frequencies.length; i++)
System.out.printf("%s: %d, ", (char)('A' + i), frequencies[i]);









share|improve this answer











$endgroup$












  • $begingroup$
    Yes, the "resource" is from eclipse. I usually ignore it, but this time I just felt like adding it.
    $endgroup$
    – Artemis Hunter
    5 hours ago










  • $begingroup$
    It would probably be a good idea to check that inputChar is an uppercase letter. The code fails with ArrayIndexOutOfBoundsException otherwise.
    $endgroup$
    – Eric Duminil
    1 hour ago










  • $begingroup$
    @EricDuminil. I convert the whole string to uppercase, so that should be taken care of: String input = scanner.nextLine().toUpperCase();. Should it still be checked withCharacter.isUpperCase()? Of course, this code fails in many ways if there are non-ASCII characters in the input. But ASCII was an implicit requirement also for the original code. I could have mentioned it, though.
    $endgroup$
    – TomG
    10 mins ago


















1












$begingroup$

You can use hash map in java to calculate the frequency of characters in a string



import java.util.Map;
import java.util.HashMap;

public class Letters
public static void main(String[] args)

String str = "check repeated alphabets from a string ";

int len = str.length();

Map<Character, Integer> numChars = new HashMap<Character, Integer>(Math.min(len, 26));

for (int i = 0; i < len; ++i)

char charAt = str.charAt(i);

if (!numChars.containsKey(charAt))

numChars.put(charAt, 1);

else

numChars.put(charAt, numChars.get(charAt) + 1);



System.out.println(numChars);





Result



" " =5, a=5, b=1, c=2, d=1, e=6, h=3, k=1, l=1, m=1, n=1, o=1, p=2, r=2, s=1, t=2, w=1, y=1 





share|improve this answer








New contributor




Vishal Dhanotiya is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$












  • $begingroup$
    You are providing an alternative implementation, but no review of the original code. Could you update your post to cover some aspects of the code?
    $endgroup$
    – TomG
    7 hours ago










  • $begingroup$
    He asks for both review or alternative solutions that's why I am providing this solution ok no issue I will review his code and provide my feedback on it
    $endgroup$
    – Vishal Dhanotiya
    7 hours ago










  • $begingroup$
    I actually don't mind an alternate implementation as well. I'd be eager to learn about the different ways I can approach a certain task. While I do not know just yet how Map and HashMap work, it does seem a lot simpler than the approach I took.
    $endgroup$
    – Artemis Hunter
    7 hours ago










Your Answer





StackExchange.ifUsing("editor", function ()
return StackExchange.using("mathjaxEditing", function ()
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
);
);
, "mathjax-editing");

StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);






Artemis Hunter is a new contributor. Be nice, and check out our Code of Conduct.









draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215592%2fcalculate-the-frequency-of-characters-in-a-string%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes









3












$begingroup$

Separate logical elements



It's good to separate different logical parts of a program, for example:



  • Parse input: a function that takes an InputStream and returns a String

  • Compute frequencies: a function that takes a String and returns frequencies in some form. In your current program you used an int[], it could have been a Map<Character, Integer>.

  • Print the frequencies: a function that takes the frequencies in some form, returns nothing, and prints to screen the frequencies nicely formatted.

Computing indexes of letters



If the input string contains only uppercase letters, then you can translate those letters to array indexes in the range of 0 to 25 (inclusive) like this:



int index = ch - 'A';


This eliminates the nested loop you had.
It also eliminates the need for the c array.



Initializing arrays



Instead of this:




int[] f = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;



You could write simply int[] f = new int[26];



Instead of this:




char[] c = 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z';



I would take a lazy approach and write char[] c = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();



Use better variable names



Single-letter variable names should only be used for trivial, highly transient things.
The names f and c in the program are inappropriate, and make the program more difficult to read.






share|improve this answer









$endgroup$












  • $begingroup$
    I've been sticking to arrays because I haven't yet started learning about Maps and HashMaps. I'll be sure to check them out now... Thanks for pointing out the toCharArray() function. I was unaware that it existed.
    $endgroup$
    – Artemis Hunter
    7 hours ago










  • $begingroup$
    I didn't mean that you should use a Map. I mentioned as an option. Both ways have advantages and disadvantages, the best solution depends on the use case. Here it doesn't matter much.
    $endgroup$
    – janos
    7 hours ago










  • $begingroup$
    Understood. BTW, thought I'd point out about the variable names, I actually find it pretty convenient to go with single-letter names: c for character, f for frequency, i for iterator and so on.
    $endgroup$
    – Artemis Hunter
    6 hours ago






  • 1




    $begingroup$
    @TomG But your consumer usually wouldn't have access to your code, would they? The consumer is meant to receive the application which the code runs. In case of another coder, you might be right, but even a simple remark next to the variable's declaration might suffice, would it not? Actually, I only use single letters in my basic programs, like the one above. Usually my programs have clear names.
    $endgroup$
    – Artemis Hunter
    5 hours ago







  • 2




    $begingroup$
    @ArtemisHunter There are aspects of style that are subjective. In this example, good objective arguments exist, against comments. 1. The consumers of your binaries indeed don't care about variable names. But the consumers of your source code do: the human reviewers and maintainers. Without descriptive names, it's hard to keep in mind what f meant, you may have to scan back in the program to understand, which is a mental burden. 2. Comments can go out of sync with the code they describe. If instead of comments you write in a way that's self-descriptive, that's a better long-term solution.
    $endgroup$
    – janos
    4 hours ago















3












$begingroup$

Separate logical elements



It's good to separate different logical parts of a program, for example:



  • Parse input: a function that takes an InputStream and returns a String

  • Compute frequencies: a function that takes a String and returns frequencies in some form. In your current program you used an int[], it could have been a Map<Character, Integer>.

  • Print the frequencies: a function that takes the frequencies in some form, returns nothing, and prints to screen the frequencies nicely formatted.

Computing indexes of letters



If the input string contains only uppercase letters, then you can translate those letters to array indexes in the range of 0 to 25 (inclusive) like this:



int index = ch - 'A';


This eliminates the nested loop you had.
It also eliminates the need for the c array.



Initializing arrays



Instead of this:




int[] f = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;



You could write simply int[] f = new int[26];



Instead of this:




char[] c = 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z';



I would take a lazy approach and write char[] c = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();



Use better variable names



Single-letter variable names should only be used for trivial, highly transient things.
The names f and c in the program are inappropriate, and make the program more difficult to read.






share|improve this answer









$endgroup$












  • $begingroup$
    I've been sticking to arrays because I haven't yet started learning about Maps and HashMaps. I'll be sure to check them out now... Thanks for pointing out the toCharArray() function. I was unaware that it existed.
    $endgroup$
    – Artemis Hunter
    7 hours ago










  • $begingroup$
    I didn't mean that you should use a Map. I mentioned as an option. Both ways have advantages and disadvantages, the best solution depends on the use case. Here it doesn't matter much.
    $endgroup$
    – janos
    7 hours ago










  • $begingroup$
    Understood. BTW, thought I'd point out about the variable names, I actually find it pretty convenient to go with single-letter names: c for character, f for frequency, i for iterator and so on.
    $endgroup$
    – Artemis Hunter
    6 hours ago






  • 1




    $begingroup$
    @TomG But your consumer usually wouldn't have access to your code, would they? The consumer is meant to receive the application which the code runs. In case of another coder, you might be right, but even a simple remark next to the variable's declaration might suffice, would it not? Actually, I only use single letters in my basic programs, like the one above. Usually my programs have clear names.
    $endgroup$
    – Artemis Hunter
    5 hours ago







  • 2




    $begingroup$
    @ArtemisHunter There are aspects of style that are subjective. In this example, good objective arguments exist, against comments. 1. The consumers of your binaries indeed don't care about variable names. But the consumers of your source code do: the human reviewers and maintainers. Without descriptive names, it's hard to keep in mind what f meant, you may have to scan back in the program to understand, which is a mental burden. 2. Comments can go out of sync with the code they describe. If instead of comments you write in a way that's self-descriptive, that's a better long-term solution.
    $endgroup$
    – janos
    4 hours ago













3












3








3





$begingroup$

Separate logical elements



It's good to separate different logical parts of a program, for example:



  • Parse input: a function that takes an InputStream and returns a String

  • Compute frequencies: a function that takes a String and returns frequencies in some form. In your current program you used an int[], it could have been a Map<Character, Integer>.

  • Print the frequencies: a function that takes the frequencies in some form, returns nothing, and prints to screen the frequencies nicely formatted.

Computing indexes of letters



If the input string contains only uppercase letters, then you can translate those letters to array indexes in the range of 0 to 25 (inclusive) like this:



int index = ch - 'A';


This eliminates the nested loop you had.
It also eliminates the need for the c array.



Initializing arrays



Instead of this:




int[] f = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;



You could write simply int[] f = new int[26];



Instead of this:




char[] c = 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z';



I would take a lazy approach and write char[] c = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();



Use better variable names



Single-letter variable names should only be used for trivial, highly transient things.
The names f and c in the program are inappropriate, and make the program more difficult to read.






share|improve this answer









$endgroup$



Separate logical elements



It's good to separate different logical parts of a program, for example:



  • Parse input: a function that takes an InputStream and returns a String

  • Compute frequencies: a function that takes a String and returns frequencies in some form. In your current program you used an int[], it could have been a Map<Character, Integer>.

  • Print the frequencies: a function that takes the frequencies in some form, returns nothing, and prints to screen the frequencies nicely formatted.

Computing indexes of letters



If the input string contains only uppercase letters, then you can translate those letters to array indexes in the range of 0 to 25 (inclusive) like this:



int index = ch - 'A';


This eliminates the nested loop you had.
It also eliminates the need for the c array.



Initializing arrays



Instead of this:




int[] f = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;



You could write simply int[] f = new int[26];



Instead of this:




char[] c = 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z';



I would take a lazy approach and write char[] c = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();



Use better variable names



Single-letter variable names should only be used for trivial, highly transient things.
The names f and c in the program are inappropriate, and make the program more difficult to read.







share|improve this answer












share|improve this answer



share|improve this answer










answered 7 hours ago









janosjanos

98.6k12125350




98.6k12125350











  • $begingroup$
    I've been sticking to arrays because I haven't yet started learning about Maps and HashMaps. I'll be sure to check them out now... Thanks for pointing out the toCharArray() function. I was unaware that it existed.
    $endgroup$
    – Artemis Hunter
    7 hours ago










  • $begingroup$
    I didn't mean that you should use a Map. I mentioned as an option. Both ways have advantages and disadvantages, the best solution depends on the use case. Here it doesn't matter much.
    $endgroup$
    – janos
    7 hours ago










  • $begingroup$
    Understood. BTW, thought I'd point out about the variable names, I actually find it pretty convenient to go with single-letter names: c for character, f for frequency, i for iterator and so on.
    $endgroup$
    – Artemis Hunter
    6 hours ago






  • 1




    $begingroup$
    @TomG But your consumer usually wouldn't have access to your code, would they? The consumer is meant to receive the application which the code runs. In case of another coder, you might be right, but even a simple remark next to the variable's declaration might suffice, would it not? Actually, I only use single letters in my basic programs, like the one above. Usually my programs have clear names.
    $endgroup$
    – Artemis Hunter
    5 hours ago







  • 2




    $begingroup$
    @ArtemisHunter There are aspects of style that are subjective. In this example, good objective arguments exist, against comments. 1. The consumers of your binaries indeed don't care about variable names. But the consumers of your source code do: the human reviewers and maintainers. Without descriptive names, it's hard to keep in mind what f meant, you may have to scan back in the program to understand, which is a mental burden. 2. Comments can go out of sync with the code they describe. If instead of comments you write in a way that's self-descriptive, that's a better long-term solution.
    $endgroup$
    – janos
    4 hours ago
















  • $begingroup$
    I've been sticking to arrays because I haven't yet started learning about Maps and HashMaps. I'll be sure to check them out now... Thanks for pointing out the toCharArray() function. I was unaware that it existed.
    $endgroup$
    – Artemis Hunter
    7 hours ago










  • $begingroup$
    I didn't mean that you should use a Map. I mentioned as an option. Both ways have advantages and disadvantages, the best solution depends on the use case. Here it doesn't matter much.
    $endgroup$
    – janos
    7 hours ago










  • $begingroup$
    Understood. BTW, thought I'd point out about the variable names, I actually find it pretty convenient to go with single-letter names: c for character, f for frequency, i for iterator and so on.
    $endgroup$
    – Artemis Hunter
    6 hours ago






  • 1




    $begingroup$
    @TomG But your consumer usually wouldn't have access to your code, would they? The consumer is meant to receive the application which the code runs. In case of another coder, you might be right, but even a simple remark next to the variable's declaration might suffice, would it not? Actually, I only use single letters in my basic programs, like the one above. Usually my programs have clear names.
    $endgroup$
    – Artemis Hunter
    5 hours ago







  • 2




    $begingroup$
    @ArtemisHunter There are aspects of style that are subjective. In this example, good objective arguments exist, against comments. 1. The consumers of your binaries indeed don't care about variable names. But the consumers of your source code do: the human reviewers and maintainers. Without descriptive names, it's hard to keep in mind what f meant, you may have to scan back in the program to understand, which is a mental burden. 2. Comments can go out of sync with the code they describe. If instead of comments you write in a way that's self-descriptive, that's a better long-term solution.
    $endgroup$
    – janos
    4 hours ago















$begingroup$
I've been sticking to arrays because I haven't yet started learning about Maps and HashMaps. I'll be sure to check them out now... Thanks for pointing out the toCharArray() function. I was unaware that it existed.
$endgroup$
– Artemis Hunter
7 hours ago




$begingroup$
I've been sticking to arrays because I haven't yet started learning about Maps and HashMaps. I'll be sure to check them out now... Thanks for pointing out the toCharArray() function. I was unaware that it existed.
$endgroup$
– Artemis Hunter
7 hours ago












$begingroup$
I didn't mean that you should use a Map. I mentioned as an option. Both ways have advantages and disadvantages, the best solution depends on the use case. Here it doesn't matter much.
$endgroup$
– janos
7 hours ago




$begingroup$
I didn't mean that you should use a Map. I mentioned as an option. Both ways have advantages and disadvantages, the best solution depends on the use case. Here it doesn't matter much.
$endgroup$
– janos
7 hours ago












$begingroup$
Understood. BTW, thought I'd point out about the variable names, I actually find it pretty convenient to go with single-letter names: c for character, f for frequency, i for iterator and so on.
$endgroup$
– Artemis Hunter
6 hours ago




$begingroup$
Understood. BTW, thought I'd point out about the variable names, I actually find it pretty convenient to go with single-letter names: c for character, f for frequency, i for iterator and so on.
$endgroup$
– Artemis Hunter
6 hours ago




1




1




$begingroup$
@TomG But your consumer usually wouldn't have access to your code, would they? The consumer is meant to receive the application which the code runs. In case of another coder, you might be right, but even a simple remark next to the variable's declaration might suffice, would it not? Actually, I only use single letters in my basic programs, like the one above. Usually my programs have clear names.
$endgroup$
– Artemis Hunter
5 hours ago





$begingroup$
@TomG But your consumer usually wouldn't have access to your code, would they? The consumer is meant to receive the application which the code runs. In case of another coder, you might be right, but even a simple remark next to the variable's declaration might suffice, would it not? Actually, I only use single letters in my basic programs, like the one above. Usually my programs have clear names.
$endgroup$
– Artemis Hunter
5 hours ago





2




2




$begingroup$
@ArtemisHunter There are aspects of style that are subjective. In this example, good objective arguments exist, against comments. 1. The consumers of your binaries indeed don't care about variable names. But the consumers of your source code do: the human reviewers and maintainers. Without descriptive names, it's hard to keep in mind what f meant, you may have to scan back in the program to understand, which is a mental burden. 2. Comments can go out of sync with the code they describe. If instead of comments you write in a way that's self-descriptive, that's a better long-term solution.
$endgroup$
– janos
4 hours ago




$begingroup$
@ArtemisHunter There are aspects of style that are subjective. In this example, good objective arguments exist, against comments. 1. The consumers of your binaries indeed don't care about variable names. But the consumers of your source code do: the human reviewers and maintainers. Without descriptive names, it's hard to keep in mind what f meant, you may have to scan back in the program to understand, which is a mental burden. 2. Comments can go out of sync with the code they describe. If instead of comments you write in a way that's self-descriptive, that's a better long-term solution.
$endgroup$
– janos
4 hours ago













2












$begingroup$

Warnings



Don't use the suppresswarnings annotation for things that can be fixed easily. I don't recognize the "resource" warning, I guess it's specific to the compiler you're using (Eclipse?). Probably comes from using the Scanner without closing it properly. By using the try-with-resources -statement for anything that supports java.lang.AutoCloseable, this will be handled for you automatically.



Variables and naming



There's no point in trying to save a few keystrokes by using short variable names. The compiler doesn't care what the names are, so you can just as well use human-readable names. The exception here being de-facto standardized loop indices like i and j.



Any decent code editor or IDE will autocomplete the names for you, so it's not that much more to type. A modified section of your original code, notice how I also chained the call to toUpperCase() directly after the nextLine() call. No need to create a new variable for the case-corrected string:



Scanner inputScanner = new Scanner(System.in);
String input = inputScanner.nextLine().toUpperCase();


Object methods



Familiarize yourself with the Java standard library and API. The String class has a method for returning its contents as a char array: toCharArray(). You could use that, combined with the enhanced for loop to simplify your loop:



String input = // fetch string somehow
for (char inputChar : input.toCharArray())
// Loop processing here



Printing an array is similarly a one-line operation: System.out.println(Arrays.toString(your array here))



Tips and tricks



There's a neat(?) trick for calculations using chars in Java. As you are upper-casing all the chars, you can use 'A' as the base for the array index. So instead of having two arrays, one with the frequencies, one for the char-to-index mapping, use subtraction from 'A' to get the index:



for (char inputChar : input.toCharArray()) 
frequencies[inputChar - 'A']++;



Alternative implementation



Here's my alternative implementation using only the same data structures as in your original post. I do agree with Vishal Dhanotiya about the use of a map for this.



import java.util.Arrays;
import java.util.Scanner;

public class Letters
public static void main(String[] args)

int[] frequencies = new int[26];

try (Scanner scanner = new Scanner(System.in))
System.out.print("Enter a string: ");
String input = scanner.nextLine().toUpperCase();

for (char inputChar : input.toCharArray())
frequencies[inputChar - 'A']++;


for (int i = 0; i < frequencies.length; i++)
System.out.printf("%s: %d, ", (char)('A' + i), frequencies[i]);









share|improve this answer











$endgroup$












  • $begingroup$
    Yes, the "resource" is from eclipse. I usually ignore it, but this time I just felt like adding it.
    $endgroup$
    – Artemis Hunter
    5 hours ago










  • $begingroup$
    It would probably be a good idea to check that inputChar is an uppercase letter. The code fails with ArrayIndexOutOfBoundsException otherwise.
    $endgroup$
    – Eric Duminil
    1 hour ago










  • $begingroup$
    @EricDuminil. I convert the whole string to uppercase, so that should be taken care of: String input = scanner.nextLine().toUpperCase();. Should it still be checked withCharacter.isUpperCase()? Of course, this code fails in many ways if there are non-ASCII characters in the input. But ASCII was an implicit requirement also for the original code. I could have mentioned it, though.
    $endgroup$
    – TomG
    10 mins ago















2












$begingroup$

Warnings



Don't use the suppresswarnings annotation for things that can be fixed easily. I don't recognize the "resource" warning, I guess it's specific to the compiler you're using (Eclipse?). Probably comes from using the Scanner without closing it properly. By using the try-with-resources -statement for anything that supports java.lang.AutoCloseable, this will be handled for you automatically.



Variables and naming



There's no point in trying to save a few keystrokes by using short variable names. The compiler doesn't care what the names are, so you can just as well use human-readable names. The exception here being de-facto standardized loop indices like i and j.



Any decent code editor or IDE will autocomplete the names for you, so it's not that much more to type. A modified section of your original code, notice how I also chained the call to toUpperCase() directly after the nextLine() call. No need to create a new variable for the case-corrected string:



Scanner inputScanner = new Scanner(System.in);
String input = inputScanner.nextLine().toUpperCase();


Object methods



Familiarize yourself with the Java standard library and API. The String class has a method for returning its contents as a char array: toCharArray(). You could use that, combined with the enhanced for loop to simplify your loop:



String input = // fetch string somehow
for (char inputChar : input.toCharArray())
// Loop processing here



Printing an array is similarly a one-line operation: System.out.println(Arrays.toString(your array here))



Tips and tricks



There's a neat(?) trick for calculations using chars in Java. As you are upper-casing all the chars, you can use 'A' as the base for the array index. So instead of having two arrays, one with the frequencies, one for the char-to-index mapping, use subtraction from 'A' to get the index:



for (char inputChar : input.toCharArray()) 
frequencies[inputChar - 'A']++;



Alternative implementation



Here's my alternative implementation using only the same data structures as in your original post. I do agree with Vishal Dhanotiya about the use of a map for this.



import java.util.Arrays;
import java.util.Scanner;

public class Letters
public static void main(String[] args)

int[] frequencies = new int[26];

try (Scanner scanner = new Scanner(System.in))
System.out.print("Enter a string: ");
String input = scanner.nextLine().toUpperCase();

for (char inputChar : input.toCharArray())
frequencies[inputChar - 'A']++;


for (int i = 0; i < frequencies.length; i++)
System.out.printf("%s: %d, ", (char)('A' + i), frequencies[i]);









share|improve this answer











$endgroup$












  • $begingroup$
    Yes, the "resource" is from eclipse. I usually ignore it, but this time I just felt like adding it.
    $endgroup$
    – Artemis Hunter
    5 hours ago










  • $begingroup$
    It would probably be a good idea to check that inputChar is an uppercase letter. The code fails with ArrayIndexOutOfBoundsException otherwise.
    $endgroup$
    – Eric Duminil
    1 hour ago










  • $begingroup$
    @EricDuminil. I convert the whole string to uppercase, so that should be taken care of: String input = scanner.nextLine().toUpperCase();. Should it still be checked withCharacter.isUpperCase()? Of course, this code fails in many ways if there are non-ASCII characters in the input. But ASCII was an implicit requirement also for the original code. I could have mentioned it, though.
    $endgroup$
    – TomG
    10 mins ago













2












2








2





$begingroup$

Warnings



Don't use the suppresswarnings annotation for things that can be fixed easily. I don't recognize the "resource" warning, I guess it's specific to the compiler you're using (Eclipse?). Probably comes from using the Scanner without closing it properly. By using the try-with-resources -statement for anything that supports java.lang.AutoCloseable, this will be handled for you automatically.



Variables and naming



There's no point in trying to save a few keystrokes by using short variable names. The compiler doesn't care what the names are, so you can just as well use human-readable names. The exception here being de-facto standardized loop indices like i and j.



Any decent code editor or IDE will autocomplete the names for you, so it's not that much more to type. A modified section of your original code, notice how I also chained the call to toUpperCase() directly after the nextLine() call. No need to create a new variable for the case-corrected string:



Scanner inputScanner = new Scanner(System.in);
String input = inputScanner.nextLine().toUpperCase();


Object methods



Familiarize yourself with the Java standard library and API. The String class has a method for returning its contents as a char array: toCharArray(). You could use that, combined with the enhanced for loop to simplify your loop:



String input = // fetch string somehow
for (char inputChar : input.toCharArray())
// Loop processing here



Printing an array is similarly a one-line operation: System.out.println(Arrays.toString(your array here))



Tips and tricks



There's a neat(?) trick for calculations using chars in Java. As you are upper-casing all the chars, you can use 'A' as the base for the array index. So instead of having two arrays, one with the frequencies, one for the char-to-index mapping, use subtraction from 'A' to get the index:



for (char inputChar : input.toCharArray()) 
frequencies[inputChar - 'A']++;



Alternative implementation



Here's my alternative implementation using only the same data structures as in your original post. I do agree with Vishal Dhanotiya about the use of a map for this.



import java.util.Arrays;
import java.util.Scanner;

public class Letters
public static void main(String[] args)

int[] frequencies = new int[26];

try (Scanner scanner = new Scanner(System.in))
System.out.print("Enter a string: ");
String input = scanner.nextLine().toUpperCase();

for (char inputChar : input.toCharArray())
frequencies[inputChar - 'A']++;


for (int i = 0; i < frequencies.length; i++)
System.out.printf("%s: %d, ", (char)('A' + i), frequencies[i]);









share|improve this answer











$endgroup$



Warnings



Don't use the suppresswarnings annotation for things that can be fixed easily. I don't recognize the "resource" warning, I guess it's specific to the compiler you're using (Eclipse?). Probably comes from using the Scanner without closing it properly. By using the try-with-resources -statement for anything that supports java.lang.AutoCloseable, this will be handled for you automatically.



Variables and naming



There's no point in trying to save a few keystrokes by using short variable names. The compiler doesn't care what the names are, so you can just as well use human-readable names. The exception here being de-facto standardized loop indices like i and j.



Any decent code editor or IDE will autocomplete the names for you, so it's not that much more to type. A modified section of your original code, notice how I also chained the call to toUpperCase() directly after the nextLine() call. No need to create a new variable for the case-corrected string:



Scanner inputScanner = new Scanner(System.in);
String input = inputScanner.nextLine().toUpperCase();


Object methods



Familiarize yourself with the Java standard library and API. The String class has a method for returning its contents as a char array: toCharArray(). You could use that, combined with the enhanced for loop to simplify your loop:



String input = // fetch string somehow
for (char inputChar : input.toCharArray())
// Loop processing here



Printing an array is similarly a one-line operation: System.out.println(Arrays.toString(your array here))



Tips and tricks



There's a neat(?) trick for calculations using chars in Java. As you are upper-casing all the chars, you can use 'A' as the base for the array index. So instead of having two arrays, one with the frequencies, one for the char-to-index mapping, use subtraction from 'A' to get the index:



for (char inputChar : input.toCharArray()) 
frequencies[inputChar - 'A']++;



Alternative implementation



Here's my alternative implementation using only the same data structures as in your original post. I do agree with Vishal Dhanotiya about the use of a map for this.



import java.util.Arrays;
import java.util.Scanner;

public class Letters
public static void main(String[] args)

int[] frequencies = new int[26];

try (Scanner scanner = new Scanner(System.in))
System.out.print("Enter a string: ");
String input = scanner.nextLine().toUpperCase();

for (char inputChar : input.toCharArray())
frequencies[inputChar - 'A']++;


for (int i = 0; i < frequencies.length; i++)
System.out.printf("%s: %d, ", (char)('A' + i), frequencies[i]);










share|improve this answer














share|improve this answer



share|improve this answer








edited 6 hours ago

























answered 6 hours ago









TomGTomG

40627




40627











  • $begingroup$
    Yes, the "resource" is from eclipse. I usually ignore it, but this time I just felt like adding it.
    $endgroup$
    – Artemis Hunter
    5 hours ago










  • $begingroup$
    It would probably be a good idea to check that inputChar is an uppercase letter. The code fails with ArrayIndexOutOfBoundsException otherwise.
    $endgroup$
    – Eric Duminil
    1 hour ago










  • $begingroup$
    @EricDuminil. I convert the whole string to uppercase, so that should be taken care of: String input = scanner.nextLine().toUpperCase();. Should it still be checked withCharacter.isUpperCase()? Of course, this code fails in many ways if there are non-ASCII characters in the input. But ASCII was an implicit requirement also for the original code. I could have mentioned it, though.
    $endgroup$
    – TomG
    10 mins ago
















  • $begingroup$
    Yes, the "resource" is from eclipse. I usually ignore it, but this time I just felt like adding it.
    $endgroup$
    – Artemis Hunter
    5 hours ago










  • $begingroup$
    It would probably be a good idea to check that inputChar is an uppercase letter. The code fails with ArrayIndexOutOfBoundsException otherwise.
    $endgroup$
    – Eric Duminil
    1 hour ago










  • $begingroup$
    @EricDuminil. I convert the whole string to uppercase, so that should be taken care of: String input = scanner.nextLine().toUpperCase();. Should it still be checked withCharacter.isUpperCase()? Of course, this code fails in many ways if there are non-ASCII characters in the input. But ASCII was an implicit requirement also for the original code. I could have mentioned it, though.
    $endgroup$
    – TomG
    10 mins ago















$begingroup$
Yes, the "resource" is from eclipse. I usually ignore it, but this time I just felt like adding it.
$endgroup$
– Artemis Hunter
5 hours ago




$begingroup$
Yes, the "resource" is from eclipse. I usually ignore it, but this time I just felt like adding it.
$endgroup$
– Artemis Hunter
5 hours ago












$begingroup$
It would probably be a good idea to check that inputChar is an uppercase letter. The code fails with ArrayIndexOutOfBoundsException otherwise.
$endgroup$
– Eric Duminil
1 hour ago




$begingroup$
It would probably be a good idea to check that inputChar is an uppercase letter. The code fails with ArrayIndexOutOfBoundsException otherwise.
$endgroup$
– Eric Duminil
1 hour ago












$begingroup$
@EricDuminil. I convert the whole string to uppercase, so that should be taken care of: String input = scanner.nextLine().toUpperCase();. Should it still be checked withCharacter.isUpperCase()? Of course, this code fails in many ways if there are non-ASCII characters in the input. But ASCII was an implicit requirement also for the original code. I could have mentioned it, though.
$endgroup$
– TomG
10 mins ago




$begingroup$
@EricDuminil. I convert the whole string to uppercase, so that should be taken care of: String input = scanner.nextLine().toUpperCase();. Should it still be checked withCharacter.isUpperCase()? Of course, this code fails in many ways if there are non-ASCII characters in the input. But ASCII was an implicit requirement also for the original code. I could have mentioned it, though.
$endgroup$
– TomG
10 mins ago











1












$begingroup$

You can use hash map in java to calculate the frequency of characters in a string



import java.util.Map;
import java.util.HashMap;

public class Letters
public static void main(String[] args)

String str = "check repeated alphabets from a string ";

int len = str.length();

Map<Character, Integer> numChars = new HashMap<Character, Integer>(Math.min(len, 26));

for (int i = 0; i < len; ++i)

char charAt = str.charAt(i);

if (!numChars.containsKey(charAt))

numChars.put(charAt, 1);

else

numChars.put(charAt, numChars.get(charAt) + 1);



System.out.println(numChars);





Result



" " =5, a=5, b=1, c=2, d=1, e=6, h=3, k=1, l=1, m=1, n=1, o=1, p=2, r=2, s=1, t=2, w=1, y=1 





share|improve this answer








New contributor




Vishal Dhanotiya is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$












  • $begingroup$
    You are providing an alternative implementation, but no review of the original code. Could you update your post to cover some aspects of the code?
    $endgroup$
    – TomG
    7 hours ago










  • $begingroup$
    He asks for both review or alternative solutions that's why I am providing this solution ok no issue I will review his code and provide my feedback on it
    $endgroup$
    – Vishal Dhanotiya
    7 hours ago










  • $begingroup$
    I actually don't mind an alternate implementation as well. I'd be eager to learn about the different ways I can approach a certain task. While I do not know just yet how Map and HashMap work, it does seem a lot simpler than the approach I took.
    $endgroup$
    – Artemis Hunter
    7 hours ago















1












$begingroup$

You can use hash map in java to calculate the frequency of characters in a string



import java.util.Map;
import java.util.HashMap;

public class Letters
public static void main(String[] args)

String str = "check repeated alphabets from a string ";

int len = str.length();

Map<Character, Integer> numChars = new HashMap<Character, Integer>(Math.min(len, 26));

for (int i = 0; i < len; ++i)

char charAt = str.charAt(i);

if (!numChars.containsKey(charAt))

numChars.put(charAt, 1);

else

numChars.put(charAt, numChars.get(charAt) + 1);



System.out.println(numChars);





Result



" " =5, a=5, b=1, c=2, d=1, e=6, h=3, k=1, l=1, m=1, n=1, o=1, p=2, r=2, s=1, t=2, w=1, y=1 





share|improve this answer








New contributor




Vishal Dhanotiya is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$












  • $begingroup$
    You are providing an alternative implementation, but no review of the original code. Could you update your post to cover some aspects of the code?
    $endgroup$
    – TomG
    7 hours ago










  • $begingroup$
    He asks for both review or alternative solutions that's why I am providing this solution ok no issue I will review his code and provide my feedback on it
    $endgroup$
    – Vishal Dhanotiya
    7 hours ago










  • $begingroup$
    I actually don't mind an alternate implementation as well. I'd be eager to learn about the different ways I can approach a certain task. While I do not know just yet how Map and HashMap work, it does seem a lot simpler than the approach I took.
    $endgroup$
    – Artemis Hunter
    7 hours ago













1












1








1





$begingroup$

You can use hash map in java to calculate the frequency of characters in a string



import java.util.Map;
import java.util.HashMap;

public class Letters
public static void main(String[] args)

String str = "check repeated alphabets from a string ";

int len = str.length();

Map<Character, Integer> numChars = new HashMap<Character, Integer>(Math.min(len, 26));

for (int i = 0; i < len; ++i)

char charAt = str.charAt(i);

if (!numChars.containsKey(charAt))

numChars.put(charAt, 1);

else

numChars.put(charAt, numChars.get(charAt) + 1);



System.out.println(numChars);





Result



" " =5, a=5, b=1, c=2, d=1, e=6, h=3, k=1, l=1, m=1, n=1, o=1, p=2, r=2, s=1, t=2, w=1, y=1 





share|improve this answer








New contributor




Vishal Dhanotiya is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$



You can use hash map in java to calculate the frequency of characters in a string



import java.util.Map;
import java.util.HashMap;

public class Letters
public static void main(String[] args)

String str = "check repeated alphabets from a string ";

int len = str.length();

Map<Character, Integer> numChars = new HashMap<Character, Integer>(Math.min(len, 26));

for (int i = 0; i < len; ++i)

char charAt = str.charAt(i);

if (!numChars.containsKey(charAt))

numChars.put(charAt, 1);

else

numChars.put(charAt, numChars.get(charAt) + 1);



System.out.println(numChars);





Result



" " =5, a=5, b=1, c=2, d=1, e=6, h=3, k=1, l=1, m=1, n=1, o=1, p=2, r=2, s=1, t=2, w=1, y=1 






share|improve this answer








New contributor




Vishal Dhanotiya is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this answer



share|improve this answer






New contributor




Vishal Dhanotiya is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









answered 9 hours ago









Vishal DhanotiyaVishal Dhanotiya

111




111




New contributor




Vishal Dhanotiya is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Vishal Dhanotiya is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Vishal Dhanotiya is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











  • $begingroup$
    You are providing an alternative implementation, but no review of the original code. Could you update your post to cover some aspects of the code?
    $endgroup$
    – TomG
    7 hours ago










  • $begingroup$
    He asks for both review or alternative solutions that's why I am providing this solution ok no issue I will review his code and provide my feedback on it
    $endgroup$
    – Vishal Dhanotiya
    7 hours ago










  • $begingroup$
    I actually don't mind an alternate implementation as well. I'd be eager to learn about the different ways I can approach a certain task. While I do not know just yet how Map and HashMap work, it does seem a lot simpler than the approach I took.
    $endgroup$
    – Artemis Hunter
    7 hours ago
















  • $begingroup$
    You are providing an alternative implementation, but no review of the original code. Could you update your post to cover some aspects of the code?
    $endgroup$
    – TomG
    7 hours ago










  • $begingroup$
    He asks for both review or alternative solutions that's why I am providing this solution ok no issue I will review his code and provide my feedback on it
    $endgroup$
    – Vishal Dhanotiya
    7 hours ago










  • $begingroup$
    I actually don't mind an alternate implementation as well. I'd be eager to learn about the different ways I can approach a certain task. While I do not know just yet how Map and HashMap work, it does seem a lot simpler than the approach I took.
    $endgroup$
    – Artemis Hunter
    7 hours ago















$begingroup$
You are providing an alternative implementation, but no review of the original code. Could you update your post to cover some aspects of the code?
$endgroup$
– TomG
7 hours ago




$begingroup$
You are providing an alternative implementation, but no review of the original code. Could you update your post to cover some aspects of the code?
$endgroup$
– TomG
7 hours ago












$begingroup$
He asks for both review or alternative solutions that's why I am providing this solution ok no issue I will review his code and provide my feedback on it
$endgroup$
– Vishal Dhanotiya
7 hours ago




$begingroup$
He asks for both review or alternative solutions that's why I am providing this solution ok no issue I will review his code and provide my feedback on it
$endgroup$
– Vishal Dhanotiya
7 hours ago












$begingroup$
I actually don't mind an alternate implementation as well. I'd be eager to learn about the different ways I can approach a certain task. While I do not know just yet how Map and HashMap work, it does seem a lot simpler than the approach I took.
$endgroup$
– Artemis Hunter
7 hours ago




$begingroup$
I actually don't mind an alternate implementation as well. I'd be eager to learn about the different ways I can approach a certain task. While I do not know just yet how Map and HashMap work, it does seem a lot simpler than the approach I took.
$endgroup$
– Artemis Hunter
7 hours ago










Artemis Hunter is a new contributor. Be nice, and check out our Code of Conduct.









draft saved

draft discarded


















Artemis Hunter is a new contributor. Be nice, and check out our Code of Conduct.












Artemis Hunter is a new contributor. Be nice, and check out our Code of Conduct.











Artemis Hunter is a new contributor. Be nice, and check out our Code of Conduct.














Thanks for contributing an answer to Code Review Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

Use MathJax to format equations. MathJax reference.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215592%2fcalculate-the-frequency-of-characters-in-a-string%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Færeyskur hestur Heimild | Tengill | Tilvísanir | LeiðsagnarvalRossið - síða um færeyska hrossið á færeyskuGott ár hjá færeyska hestinum

He _____ here since 1970 . Answer needed [closed]What does “since he was so high” mean?Meaning of “catch birds for”?How do I ensure “since” takes the meaning I want?“Who cares here” meaningWhat does “right round toward” mean?the time tense (had now been detected)What does the phrase “ring around the roses” mean here?Correct usage of “visited upon”Meaning of “foiled rail sabotage bid”It was the third time I had gone to Rome or It is the third time I had been to Rome

Slayer Innehåll Historia | Stil, komposition och lyrik | Bandets betydelse och framgångar | Sidoprojekt och samarbeten | Kontroverser | Medlemmar | Utmärkelser och nomineringar | Turnéer och festivaler | Diskografi | Referenser | Externa länkar | Navigeringsmenywww.slayer.net”Metal Massacre vol. 1””Metal Massacre vol. 3””Metal Massacre Volume III””Show No Mercy””Haunting the Chapel””Live Undead””Hell Awaits””Reign in Blood””Reign in Blood””Gold & Platinum – Reign in Blood””Golden Gods Awards Winners”originalet”Kerrang! Hall Of Fame””Slayer Looks Back On 37-Year Career In New Video Series: Part Two””South of Heaven””Gold & Platinum – South of Heaven””Seasons in the Abyss””Gold & Platinum - Seasons in the Abyss””Divine Intervention””Divine Intervention - Release group by Slayer””Gold & Platinum - Divine Intervention””Live Intrusion””Undisputed Attitude””Abolish Government/Superficial Love””Release “Slatanic Slaughter: A Tribute to Slayer” by Various Artists””Diabolus in Musica””Soundtrack to the Apocalypse””God Hates Us All””Systematic - Relationships””War at the Warfield””Gold & Platinum - War at the Warfield””Soundtrack to the Apocalypse””Gold & Platinum - Still Reigning””Metallica, Slayer, Iron Mauden Among Winners At Metal Hammer Awards””Eternal Pyre””Eternal Pyre - Slayer release group””Eternal Pyre””Metal Storm Awards 2006””Kerrang! Hall Of Fame””Slayer Wins 'Best Metal' Grammy Award””Slayer Guitarist Jeff Hanneman Dies””Bullet-For My Valentine booed at Metal Hammer Golden Gods Awards””Unholy Aliance””The End Of Slayer?””Slayer: We Could Thrash Out Two More Albums If We're Fast Enough...””'The Unholy Alliance: Chapter III' UK Dates Added”originalet”Megadeth And Slayer To Co-Headline 'Canadian Carnage' Trek”originalet”World Painted Blood””Release “World Painted Blood” by Slayer””Metallica Heading To Cinemas””Slayer, Megadeth To Join Forces For 'European Carnage' Tour - Dec. 18, 2010”originalet”Slayer's Hanneman Contracts Acute Infection; Band To Bring In Guest Guitarist””Cannibal Corpse's Pat O'Brien Will Step In As Slayer's Guest Guitarist”originalet”Slayer’s Jeff Hanneman Dead at 49””Dave Lombardo Says He Made Only $67,000 In 2011 While Touring With Slayer””Slayer: We Do Not Agree With Dave Lombardo's Substance Or Timeline Of Events””Slayer Welcomes Drummer Paul Bostaph Back To The Fold””Slayer Hope to Unveil Never-Before-Heard Jeff Hanneman Material on Next Album””Slayer Debut New Song 'Implode' During Surprise Golden Gods Appearance””Release group Repentless by Slayer””Repentless - Slayer - Credits””Slayer””Metal Storm Awards 2015””Slayer - to release comic book "Repentless #1"””Slayer To Release 'Repentless' 6.66" Vinyl Box Set””BREAKING NEWS: Slayer Announce Farewell Tour””Slayer Recruit Lamb of God, Anthrax, Behemoth + Testament for Final Tour””Slayer lägger ner efter 37 år””Slayer Announces Second North American Leg Of 'Final' Tour””Final World Tour””Slayer Announces Final European Tour With Lamb of God, Anthrax And Obituary””Slayer To Tour Europe With Lamb of God, Anthrax And Obituary””Slayer To Play 'Last French Show Ever' At Next Year's Hellfst””Slayer's Final World Tour Will Extend Into 2019””Death Angel's Rob Cavestany On Slayer's 'Farewell' Tour: 'Some Of Us Could See This Coming'””Testament Has No Plans To Retire Anytime Soon, Says Chuck Billy””Anthrax's Scott Ian On Slayer's 'Farewell' Tour Plans: 'I Was Surprised And I Wasn't Surprised'””Slayer””Slayer's Morbid Schlock””Review/Rock; For Slayer, the Mania Is the Message””Slayer - Biography””Slayer - Reign In Blood”originalet”Dave Lombardo””An exclusive oral history of Slayer”originalet”Exclusive! Interview With Slayer Guitarist Jeff Hanneman”originalet”Thinking Out Loud: Slayer's Kerry King on hair metal, Satan and being polite””Slayer Lyrics””Slayer - Biography””Most influential artists for extreme metal music””Slayer - Reign in Blood””Slayer guitarist Jeff Hanneman dies aged 49””Slatanic Slaughter: A Tribute to Slayer””Gateway to Hell: A Tribute to Slayer””Covered In Blood””Slayer: The Origins of Thrash in San Francisco, CA.””Why They Rule - #6 Slayer”originalet”Guitar World's 100 Greatest Heavy Metal Guitarists Of All Time”originalet”The fans have spoken: Slayer comes out on top in readers' polls”originalet”Tribute to Jeff Hanneman (1964-2013)””Lamb Of God Frontman: We Sound Like A Slayer Rip-Off””BEHEMOTH Frontman Pays Tribute To SLAYER's JEFF HANNEMAN””Slayer, Hatebreed Doing Double Duty On This Year's Ozzfest””System of a Down””Lacuna Coil’s Andrea Ferro Talks Influences, Skateboarding, Band Origins + More””Slayer - Reign in Blood””Into The Lungs of Hell””Slayer rules - en utställning om fans””Slayer and Their Fans Slashed Through a No-Holds-Barred Night at Gas Monkey””Home””Slayer””Gold & Platinum - The Big 4 Live from Sofia, Bulgaria””Exclusive! Interview With Slayer Guitarist Kerry King””2008-02-23: Wiltern, Los Angeles, CA, USA””Slayer's Kerry King To Perform With Megadeth Tonight! - Oct. 21, 2010”originalet”Dave Lombardo - Biography”Slayer Case DismissedArkiveradUltimate Classic Rock: Slayer guitarist Jeff Hanneman dead at 49.”Slayer: "We could never do any thing like Some Kind Of Monster..."””Cannibal Corpse'S Pat O'Brien Will Step In As Slayer'S Guest Guitarist | The Official Slayer Site”originalet”Slayer Wins 'Best Metal' Grammy Award””Slayer Guitarist Jeff Hanneman Dies””Kerrang! Awards 2006 Blog: Kerrang! Hall Of Fame””Kerrang! Awards 2013: Kerrang! Legend”originalet”Metallica, Slayer, Iron Maien Among Winners At Metal Hammer Awards””Metal Hammer Golden Gods Awards””Bullet For My Valentine Booed At Metal Hammer Golden Gods Awards””Metal Storm Awards 2006””Metal Storm Awards 2015””Slayer's Concert History””Slayer - Relationships””Slayer - Releases”Slayers officiella webbplatsSlayer på MusicBrainzOfficiell webbplatsSlayerSlayerr1373445760000 0001 1540 47353068615-5086262726cb13906545x(data)6033143kn20030215029