how to print count of each character in a string using java - java

Hey I am trying to figure out the logic in counting the each character in a string by comparing it to the first character in the string but I cannot seem to figure out the rest. If anyone can help complete this.
public class Main {
public static void main(String[] args) {
String word = "AaaaABBbccKLk";
countLetter(word);
}
public static void countLetter(String word){
int count = 0;
char firstChar = word.toLowerCase().charAt(0);
char ch;
for(int i = 0 ; i<word.length(); i++){
ch = word.toLowerCase().charAt(i);
if(ch == firstChar){
System.out.println(ch + "=" + count);
count++;
}
if(ch != firstChar && count > 0){
count=0;
System.out.println(ch + "=" + count);
count= count + 1;
}
}
}
}

I assume you may want something like this:
class Main {
public static void main(String[] args) {
String word = "AaaaABBbccKLk";
countLetter(word);
}
public static void countLetter(String word){
int[] charCount = new int[26];
word = word.toLowerCase();
for(int i = 0; i < word.length(); i++){
char letter = word.charAt(i);
int index = (int)letter - 97;
charCount[index]++;
}
for(int i = 0; i < charCount.length; i++){
System.out.println("Occurrences of " + (char)(i + 97) + " :" + charCount[i]);
}
}
}
Though this code only works for Strings with characters A-Z, you can easily make this work for a larger range of characters by expanding the size of charCount and using an ASCII table.
The way this code works is that it creates an integer array of size 26 (the number of English letters) and then lowercases the String because in programming, lowercase and uppercase letters are actually different.
Next, we iterate through the word and convert every letter into an index by converting it to its ASCII value and subtracting 97 so that we get characters in the range 0 to 25. This means that we can assign each letter to an index in our array, charCount.
From here, we just increment the element of our array that corresponds to the index of each letter.
Finally, we just print out every letter and its frequency.
Let me know if you have any questions! (Also in the future, try to give a bit more insight into your process so it is easier to guide you instead of just giving the answer).

Related

Program counts dots(.) as alphabetic characters

So my task was to create a program that takes a file as input and counts the occurrences of each alphabetic character in it. Then I shall print the letter, the amount of times it occurs and the frequency of it.
And I get it to work almost as planned. The only problem I have is that when I print, it also prints the number of dots(.) in the file. And I can't stop it from doing that. Help please..
public class CountOccurences {
private static Scanner input;
public static void main(String [] args) throws FileNotFoundException {
DecimalFormat dec = new DecimalFormat("#.000");
input = new Scanner(new File("story.txt"));
int[] ltrCtr = new int[127]; // This array counts the number of occurences for every letter / symbol on the ascii table.
String str = "";
// Puts the textfile as a String
while(input.hasNext()) {
str += input.next();
}
char[] text = str.toCharArray();
char temp; int tempInt;
int ctr = 0;
for(int i = 0; i < text.length; i++) { // Loops through the text
temp = text[i]; // Gets the char at i
tempInt = (int)temp; // Get the ascii value of the char at i
ltrCtr[tempInt]++;
if(Character.isAlphabetic(text[i])) {
ctr++;
}
}
System.out.println("Letter" + " Amount" + " Freq");
for(int i = 0; i < ltrCtr.length; i++) {
if(ltrCtr[i] >= 1 && (int)ltrCtr[i] != 46) {
System.out.println(" " + (char)i + " " +
ltrCtr[i] + " " +
dec.format((double)ltrCtr[i]/ctr) + "%");
}
}
input.close();
}
}
I believe you meant to use isLetter, not isAlphabetic.
Mureinik is right, isLetter solves your problem. Here's a post explaining the differences between isLetter and isAlphabetic to make it clearer: What is the difference between Character.isAlphabetic and Character.isLetter in Java?

Counting upper-case characters in array with strings

So i'm trying to count the number of upper-case characters in a array with strings. I'm at a brick wall here. If someone could shed some light on my problem that would be fantastic.
I assume the same loop can be done with just Character.isLowerCase(item) as well right?
After this is completed I also have to tell the user the longest string in the array and how many characters the longest string has as well which I really don't know how to do.
Professor really threw a curve ball at us with this one..
So here's my code so far:
// Program3.java
// Brandin Yoder
// 2/23/18
// Store strings in an array and tell user number of upper-case and lower-case characters,
// and spaces
import java.util.Scanner;
public class Program3
{
public static void main(String[] args)
{
// Set up keyboard.
Scanner keyboard = new Scanner(System.in);
// Input number of strings to store.
System.out.print("Number of strings to input: ");
int nrStrings = keyboard.nextInt();
// Clear keyboard buffer.
keyboard.nextLine();
// Set up array to hold strings.
String[] strings = new String[nrStrings];
// Input strings from keyboard.
System.out.println("\nInput strings:");
for(int ctr = 0; ctr < nrStrings; ctr++)
{
System.out.print("String #" + (ctr+1) + " :");
strings[ctr] = keyboard.next();
}
// Print back strings input.
System.out.println("\nStrings input:");
for(int ctr = 0; ctr < nrStrings; ctr++)
{
System.out.println("String #" + (ctr+1) + ": " + strings[ctr]);
}
// Set up variables for upper-case, lower-case and white space calculator.
int UpperNr = 0;
int LowerNr = 0;
int Spaces = 0;
// For loop that determines amount of Upper-Case numbers.
for(int ctr = 0; ctr < nrStrings; ctr++)
{
char item = strings[ctr].charAt(ctr);
if(Character.isUpperCase(item))
UpperNr++;
}
System.out.println(UpperNr);
}
}
You need to create variables to hold the data that you want to print out at the end. In this case you need to maintain an array that has the number of Uppercases for each string as well as the index and length of the longest string. You have to use a nested for loop to iterate through the array of strings that you have and also the strings themselves in order to check how many Uppercase characters you have. I have modified/commented the last part of your code below.
//array that contains number of uppercase letters in each string
int[] upperAmount = new int[nrStrings];
//index of the longest string
int maxLenIndex = 0;
//length of longest string
int maxLength = 0;
//array that iterates through all the strings in the array strings[]
for(int i = 0; i<strings.length;i++){
//if the new string is the longest
if(strings[i].length() > maxLength){
//set maxlength to the new length and record index of string
maxLength = strings[i].length();
maxLenIndex = i;
}
// For loop that determines amount of Upper-Case numbers.
for(int ctr = 0; ctr < strings[i].length(); ctr++)
{
char item = strings[i].charAt(ctr);
if(Character.isUpperCase(item))
UpperNr++;
}
//add number of uppercases to upperAmount array indexes will be the same
upperAmount[i] = UpperNr;
//reset upper number
UpperNr = 0;
}
// Print back strings input.
System.out.println("\nStrings input:");
for(int ctr = 0; ctr < nrStrings; ctr++)
{
System.out.println("String #" + (ctr+1) + ": " + strings[ctr]);
System.out.println("Number of Uppercase Letters: " + upperAmount[ctr]);
}
System.out.println("MaxStringLength: " + maxLength);
System.out.println("Max String: " + strings[maxLenIndex]);
}
I hope this solves your problem
//after you finish printing the strings
String strMax="";
int ctr=0;
for(String str :strings ){
strMax = str.length()>strMax.length()?str:strMax;
if(!str.equals(str.toLowerCase())){
for(char c : str.toCharArray()){
if(Character.isUpperCase(c))
ctr++;
}
}
}
System.out.println("Longeset String"+strMax );
System.out.println("total Upper case chars" +ctr);
Is it neccesarry to input the count of strings? I think you can accept one whole string and convert it into array of chars
char[] charArray = acceptedString.toCharArray;
Then go throw all chars, and where charArray[n] > 64 && charArray[n] < 91 increase your variable to counting UpperCases. Hope you understand) Ask if you have questions.
Scanner keyboard = new Scanner(System.in);
String inString = keyboard.nextLine();
char[] symbol = inString.toCharArray();
int count =0;
for(int i =0; i < symbol.length; i++){
if(symbol[i] > 64 && symbol[i] < 91){ //cause every char has its own number in Unicode. 'A' = 65 and 'Z' = 90
count++;
}
}
System.out.print(count);

Counting Upper and Lower characters in a string using an array

I have been working on this problem for two days now and have no idea where I'm going wrong.
Essentially I need to ask a user for a string of words.
I need to set up an int array of 26 elements that holds the count of lower case letters and one for upper case letters.
I can't get the program to compare with the array elements properly. This is my code so far:
public class Lab17Array {
public static void main(String[] args)
{
Scanner kb = new Scanner (System.in);
int lLetter = 0;
int uLetter = 0;
// int[] alph = new int [26];
int alph [] = {'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 Alph [] = {'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'};
System.out.println("Enter a phrase");
String user = kb.nextLine();
// to print out length of word
System.out.println("Total number of letters is " + user.length());
for(int i = 0; i < user.length(); i++)
{
}
System.out.println("Upper case letters are:" + uLetter);
System.out.println("Lower case letters are:" + lLetter);
int otherL = user.length() - (uLetter + lLetter);
// to print out other chars that aren't letters
System.out.println("Number of all other letters is " + otherL );
}
}
Inside my for loop is where I've been trying different if conditions. I have no idea what I'm missing?
Using an Array
You could use String.toCharArray() and a for-each loop to iterate your userInput (you seem to have changed the variable name between your post, and your comment). Regardless, something like
for (char ch : user.toCharArray()) {
if (Character.isLowerCase(ch)) {
lLetter++;
} else if (Character.isUpperCase(ch)) {
uLetter++;
}
}
Using Regular Expression(s)
You could reduce your code by using a regular expression to remove all non-lowercase characters from the input and another to remove all non-uppercase characters from the input like
int lLetter = user.replaceAll("[^a-z]", "").length(); // <-- removes everything not a-z
int uLetter = user.replaceAll("[^A-Z]", "").length(); // <-- removes everything not A-Z
Try this
int upperCount = 0;
int lowerCount = 0;
Scanner sc = new Scanner(System.in);
String w = sc.nextLine();
for(int i = 0; i < w.length(); i++){
if(Character.isUpperCase(w.charAt(i))){
upperCount++;
}else{
lowerCount++;
}
}
System.out.println("Upper Counts are "+upperCount+" lower counts are "+lowerCount);
Try this.
for(int i = 0; i < user.length(); i++)
{
int ch = user.charAt(i);
if (Arrays.binarySearch(alph, ch) >= 0)
++lLetter;
if (Arrays.binarySearch(Alph, ch) >= 0)
++uLetter;
}

Captain crunch - ROT13 encoder program

The Captain Crunch decoder ring works by taking each letter in a string and adding 13 to it. For example, 'a' becomes 'n' and 'b' becomes 'o'. The letters "wrap around" at the end, so 'z' becomes 'm'.
This is what I've got after editing it a bit from peoples comments, but now it keeps telling me that output may have not been initialized and I have no clue why... also is there anything else I need to fix in my program?
In this case, I am only concerned with encoding lowercase characters
import java.util.Scanner;
public class captainCrunch {
public static void main (String[] Args) {
Scanner sc= new Scanner(System.in);
String input;
System.out.print("getting input");
System.out.println("please enter word: ");
input= sc.next();
System.out.print(" ");
System.out.print("posting output");
System.out.print("encoding" + input + " results in: " + encode(input));
}//end of main
public static String encode(String input){
System.out.print(input.length());
int length= input.length();
int index;
String output;
char c;
String temp= " ";
for (index = 0; index < length; index++) {
c = input.charAt(index);
if (c >= 'a' && c <= 'm') c += 13;
else if (c >= 'n' && c <= 'z') c -= 13;
output= temp + (char)(c);
}
return output;
}
}
It's called ROT13 encoding.
http://en.wikipedia.org/wiki/ROT13
To fix your algorithm you just need:
public static String encodeString (String input) {
StringBuilder output = new StringBuilder();
for (int i=0;i<input.length;i++) {
char c = input.charAt(i)
output.append(c+13); // Note you will need your code to wrap the value around here
}
return output.toString();
}
I haven't implemented the "wrapping" since it depends on what case you need to support (upper or lower) etc. Essentially all you need to do though is look at the range of c and then either add or subtract 13 depending on where it is in the ASCII character set.
You don't have any loop iterating over the character of your string. You have to iterate other the string from 0 to string.length().
The output may have not been initialized:
String output = "";
If you don't put = "" then you have never initialized it (it's essentially random garbage, so the compiler won't let you do it).

Java - Histogram program

I have a program which takes a string and gives a histogram. The problem is i need the histogram to be in order... like...
letter count
a 0
b 1
c 0
.... etc. My program will just give back the letters in the string, it will not display the letters which are not in the string. here is my main program.
import java.util.*;
public class CharacterHistogram {
//scanner and method decleration
Scanner keyboard = new Scanner (System.in);
public static void generateHistogram( String input) {
// make input lower case
input=input.toLowerCase();
int lengthOfInput= input.length();
char[] Array = input.toCharArray();
//Arrays.sort(Array);
int count = 0;
// colum creation
System.out.println();
System.out.println(" Character Count");
for (int i = 0; i < lengthOfInput; i++) {
// reset count every new letter
count = 1;
for (int x = i + 1; x < lengthOfInput; x++) {
if (Array[i] == ' ') {
break;
}
if (Array[i] == Array[x]) {
count++;
Array[x] = ' ';
}
}
// check for empty char
if (Array[i] != ' ') {
System.out.println();
//row creation
System.out.println(" "+Array[i]+" "+count);
System.out.println();
}
}
}
}
here is the tester:
public class CharacterHistogramTester{
public static void main(String [] args){
String input = "4axaaafgaa5";
System.out.println("Generate Histogram for: " + input);
CharacterHistogram.generateHistogram(input);
input = " OSU won 34-10 and now have 7 wins";
System.out.println("Generate Histogram for: " + input);
CharacterHistogram.generateHistogram(input);
}
}
i would like to know if there are any ways to show all letters (even ones not used in string) alphabetically. Thank you.
P.S. i have tried the sort(Array) method and it screws up the whole program...
Create an int array of length 26, contaning the number of occurrences of each letter (0, initially).
Loop through each char of your input, and increment the integer at the appropriate index (0 for a, 1 for b, etc.).
Then print every element of the int array.
Oh, and respect the Java naming conventios: variables start with a lowercase letter.
Use a single loop to traverse the string & count letter/character occurrences, not the unnecessary & inefficient "loop within a loop" structure which you have currently.
Initialization, counting & printing the output should be separate blocks of code -- not mangled into the same block.

Categories

Resources