How to fix: Number of occurrences of a letter in a string - java

I'm trying to count the number of occurrences of letters that are in string. The code that I have written technically does what I want, but not the way I want to do it. For example, if I input "Hello World", I want my code to return "a=0 b=0 c=0 d=0 e=1 etc...." with the code I have written it returns "H=1, e=1, l=2 etc...."
Also how would I make sure that it is not case sensitive and it doesn't count spaces.
Code:
import java.util.Scanner;
public class Sequence {
private static Scanner scan = null;
public static void main(String[] args) {
scan = new Scanner(System.in);
String str = null;
System.out.print("Type text: ");
str = scan.nextLine();
int[] count = new int[255];
int length = str.length();
for (int i = 0; i < length; i++)
{
count[str.charAt(i)]++;
}
char[] ch = new char[str.length()];
for (int i = 0; i < length; i++)
{
ch[i] = str.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++)
{
if (str.charAt(i) == ch[j])
find++;
}
if (find == 1)
{
System.out.print(str.charAt(i) + "=" + count[str.charAt(i)] + " ");
}
}
}
}

As I hinted in my original comment you only need an array of 26 int(s) because there are only 26 letters in the alphabet. Before I share the code, it is important to note that Java char is an integral type (and, for example, 'a' + 1 == 'b'). That property is important, because it allows you to determine the correct offset in an array (especially if you force the input to lower case). Something like,
Scanner scan = new Scanner(System.in);
System.out.print("Type text: ");
String str = scan.nextLine();
int[] count = new int[26];
for (int i = 0; i < str.length(); i++) {
char ch = Character.toLowerCase(str.charAt(i)); // not case sensitive
if (ch >= 'a' && ch <= 'z') { // don't count "spaces" (or anything non-letter)
count[ch - 'a']++; // as 'a' + 1 == 'b', so 'b' - 'a' == 1
}
}
for (int i = 0; i < count.length; i++) {
if (count[i] != 0) {
System.out.printf("%c=%d ", 'a' + i, count[i]);
}
}
System.out.println();
If you really want to see all of the letters that have counts of zero (seems pointless to me), change
if (count[i] != 0) {
System.out.printf("%c=%d ", 'a' + i, count[i]);
}
to remove the if and just
System.out.printf("%c=%d ", 'a' + i, count[i]);

Change str = scan.nextLine(); to str = scan.nextLine().toLowerCase().replaceAll("\\s+","");
.toLowerCase() is a method which makes every char in the string lowercase.
.replaceAll() is a method which replaces one char with another. In this case, it replaces whitespaces with nothing.

Related

Counting the Number of Identical Character to its Right in a Sentence in Java

In java, I am suppose to examine each character in the sentence, from left to right and count the number of identical characters to its right and print the count.
Scanner K = new Scanner(System.in);
String s = K.nextLine();
for (int i = 0; i < s.length(); i++) {
int count = 0;
while (i+1 < s.length() && s.charAt(i)== s.charAt(i + 1))
{
i++;
count++;
}
System.out.print(s.charAt(i)+ ":");
System.out.println(count);
}
System.out.println();
}
}
Example output should be like:(when i input "I love u")
I:0
: 1
l:0
o:0
v:0
e:0
:0
u:1

Occurrences in char Array

I have this problem,
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
at Exercise_12_2.main(Exercise_12_2.java:28)
When i am trying to just simply count the occurrences of the letters in a char array. I just cant seem to wrap my head around how to work it out. I have been at it for several hours. Please help get me on the right track.
input: a a a b b c !
Expected output:
Counts:
a 3
b 2
c 1
This is my code so far. Please help me.
import java.util.Scanner;
public class Exercise_12_2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in); // Setup scanner
char[] charArray = new char[100];
int[] counts = new int[26];
char tempinput = '?';
System.out.print("Enter letters (or ! to quit): ");
while (tempinput != '!')
{
tempinput = (input.next()).charAt(0);
charArray[tempinput]++;
for (int c = 'a'; c <= 'z'; c++)
{
for (int k = 0; k <= charArray.length; k++)
{
if (c == charArray[k])
{
counts[c] += 1;
}
}
}
}
}
public static void displayCounts(int[] counts)
{
for (int i = 0; i < counts.length; i++)
{
if ((i + 1) % 10 == 0)
{
System.out.println(counts[i] + " " + (char)(i + 'a'));
}
else
{
System.out.print(counts[i] + " " + (char)(i + 'a') + " ");
}
}
}
}
java.lang.ArrayIndexOutOfBoundsException: 100 means you are asking for the 101st element of an array with only 100 elements. Remember, java arrays are indexed starting with 0.
From that you might be able to tell why this line is broken:
for (int k = 0; k <= charArray.length; k++)
charArray.length is 100, so you run up until k is 101, meaning that you try charArray[100] which is asking for the 101st element of charArray, but charArray only has 100 elements.
If you switch k <= charArray.length to k < charArray.length you should get farther.
On an unrelated note, counts[c] += 1; won't work. The int val of a char is its ascii value. The letter a for example is 97, so you'll go way off the end of your counts array. This also doesn't account for upper/lower case (which have different numeric values).
This problem becomes much easier if you use an appropriate data structure. For example, I would use a Map<Character, Integer> to keep the count and then iterate that to display. Like,
Scanner input = new Scanner(System.in); // Setup scanner
System.out.print("Enter letters (or ! to quit): ");
Map<Character, Integer> map = new HashMap<>();
char ch;
while ((ch = Character.toLowerCase(input.next().charAt(0))) != '!') {
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
System.out.println("Counts:");
for (int c = 'a'; c <= 'z'; c++) {
if (map.containsKey((char) c)) {
System.out.printf("%c\t%d%n", c, map.get((char) c));
}
}
Which I tested with your example input, and I get as requested:
Enter letters (or ! to quit): a a a b b c !
Counts:
a 3
b 2
c 1
I think after creating the character array of [a, a, b c, d, !, ..], following code will be enough to calculate count for each alphabet [a-z].
for (int k = 0; k < charArray.length; k++)
{
char c = charArray[k];
if (c >= 'a' && c <= 'z' )
{
counts[c - 'a'] += 1;
}
}

Don't know how manipulate strings

Take as input S, a string. Write a function that replaces every odd character with the character having just higher ASCII code and every even character with the character having just lower ASCII code. Print the value returned.
package assignments;
import java.util.Scanner;
public class strings_odd_even_char {
static Scanner scn = new Scanner(System.in);
public static void main(String[] args) {
String str = scn.nextLine();
for (int i = 0; i < str.length(); i = i + 2) {
char ch = str.charAt(i);
ch = (char)((ch + 1));
System.out.println(ch);
}
for (int j = 1; j < str.length(); j = j + 2) {
char ch = str.charAt(j);
ch = (char)((ch - 1));
System.out.print(ch);
}
}
}
The problem with my code is that it is first printing the values for all the odd characters and then for even characters but what I want is that they get printed in proper sequence like for input --> abcg , the output should be --> badf .
I'd hold the "incremenet" value in a variable and alternate it between +1 and -1 as I go voer the characters:
private static String change(String s) {
StringBuilder sb = new StringBuilder(s.length());
int increment = 1;
for (int i = 0; i < s.length(); ++i) {
sb.append((char)(s.charAt(i) + increment));
increment *= -1;
}
return sb.toString();
}
Just use one loop that handles both characters:
for (int i = 0; i < str.length(); i = i + 2) {
char ch = str.charAt(i);
ch = (char) (ch + 1);
System.out.print(ch);
if (i + 1 < str.length()) {
ch = str.charAt(i + 1);
ch = (char) (ch - 1);
System.out.print(ch);
}
}
You only need to iterate one time but do different operation (char+1) or (char-1) depending on the i:
public static void main(String[] args) {
String str = scn.nextLine();
for(int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if(i % 2 == 0) { // even
ch += 1;
} else { // odd
ch -= 1;
}
System.out.print(ch);
}
}
You are using two loops, but you only need one. You can use the % operator to tell if i is even or odd, and then either subtract or add accordingly:
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if(i % 2 == 0) {
ch = (char)((ch + 1));
System.out.println(ch);
} else {
ch = (char)((ch - 1));
System.out.print(ch);
}
}
You can do it in one for loop, to do that you will need to check whether the current index is even or odd. if current index is even you will increment char and print, if it is odd you will decrement char and print. to check if even or odd using % operator
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if(i%2 == 0) {
ch = ch + 1;
System.out.println(ch);
continue;
}
ch = ch - 1;
System.out.println(ch);
}

how to count the number of letters in an array java

I have an assignment about how to count the number of letters in an array.
Here is my code:
import java.util.Scanner;
public class task1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Create a scanner object
Scanner input = new Scanner(System.in);
//Prompt user's input
System.out.println("Enter strings (use a space to separate them; hit enter to finish) : ");
String str = input.nextLine();
// use split to divide the string into different words cutting by " "
String [] wordsArray = str.trim().split(" ");
System.out.println("The length of string is " + wordsArray.length);
for(int i = 0 ; i < wordsArray.length; i++){
char [] eachLetterinArray = wordsArray[i].toCharArray();
for(int j = 0,count = 0 ; j < eachLetterinArray.length; j++){
if( (eachLetterinArray[j]+'a'-97 >=65 && eachLetterinArray[j]+'a'-97 <=90 )
|| (eachLetterinArray[j]+'a'-97 >=97 && eachLetterinArray[j]+'a'-97 <=122 ) ){
count++;
}
System.out.print(count);
}
}
}
if I enter "end tr"
the output is "12312"
but what I want is "3 and 2 "
I have tried a lot and still have nothing to do about this...
can you help me?
You want to print count per word, but you are printing for each character. Just print the count variable outside of the inner loop.
for (int i = 0; i < wordsArray.length; i++) {
char[] eachLetterinArray = wordsArray[i].toCharArray();
int count = 0;
for (int j = 0; j < eachLetterinArray.length; j++) {
if ((eachLetterinArray[j] + 'a' - 97 >= 65 && eachLetterinArray[j] + 'a' - 97 <= 90)
|| (eachLetterinArray[j] + 'a' - 97 >= 97 && eachLetterinArray[j] + 'a' - 97 <= 122)) {
count++;
}
}
System.out.println(count);
}
Improvement:
Instead of the little bit complex condition, you can do this way also:
if (Character.isLetter(eachLetterinArray[j])) {
count++;
}
int countedLength = 0;
for(String string: arrayList) {
countedLength += string.length();
}
//Your count of Number of Letters in Array
System.out.pritnln(countedLength);
Or if you want to count every letter unique, do a new for in this for like
if(letter.equals("a")) {
letterVariableCountA++;
}
You are using space to split the word and count the letters. So use split() on string.
split() takes a string which splits the word. In your case it is space.
It returns splitted strings as an array. Just iterate over strings and use length() on string to get the number of characters present in the word.
public class Main
{
public static void main(String[] args)
{
int count;
String s = "This is your string for example";
String[] split = s.split(" ");
for(String str: split)
{
char[] ch = str.toCharArray(); // convert string to char array
count = 0; // reset count for every new word/string
for(char c: ch) // iterate over all the characters
{
if(Character.isLetter(c)) // Returns true if the character is a Letter
{
count++; // increase the count to represent no. of letters
}
}
System.out.print(count + " "); // print the no.of characters that are letters in a word/string.
}
}
}
This should do the trick, you were printing your count within the loop which is why it was counting. If you set the inital count value outside of it, you can then print it once the loop is complete, and then set it back to 0 before it starts on the next word.
public static void main(String[] args) {
String str = "test1 phrase";
int count = 0;
// use split to divide the string into different words cutting by " "
String[] wordsArray = str.trim().split(" ");
System.out.println("The length of string is " + wordsArray.length);
for (int i = 0; i < wordsArray.length; i++) {
char[] eachLetterinArray = wordsArray[i].toCharArray();
for (int j = 0; j < eachLetterinArray.length; j++) {
if ((eachLetterinArray[j] + 'a' - 97 >= 65 && eachLetterinArray[j] + 'a' - 97 <= 90)
|| (eachLetterinArray[j] + 'a' - 97 >= 97 && eachLetterinArray[j] + 'a' - 97 <= 122)) {
count++;
}
}
System.out.print(count + "\n");
count = 0;
}
}
with the above example I got an output of
The length of string is 2
4
6

How to use ASCII in array

I want to write a program that takes a string text, counts the appearances of every letter in English and stores them inside an array.and print the result like this:
java test abaacc
a:***
b:*
c:**
* - As many time the letter appears.
public static void main (String[] args) {
String input = args[0];
char [] letters = input.toCharArray();
System.out.println((char)97);
String a = "a:";
for (int i=0; i<letters.length; i++) {
int temp = letters[i];
i = i+97;
if (temp == (char)i) {
temp = temp + "*";
}
i = i - 97;
}
System.out.println(temp);
}
Writing (char)97 makes the code less readable. Use 'a'.
As 3kings said in a comment, you need an array of 26 counters, one for each letter of the English alphabet.
Your code should also handle both uppercase and lowercase letters.
private static void printLetterCounts(String text) {
int[] letterCount = new int[26];
for (char c : text.toCharArray())
if (c >= 'a' && c <= 'z')
letterCount[c - 'a']++;
else if (c >= 'A' && c <= 'Z')
letterCount[c - 'A']++;
for (int i = 0; i < 26; i++)
if (letterCount[i] > 0) {
char[] stars = new char[letterCount[i]];
Arrays.fill(stars, '*');
System.out.println((char)('a' + i) + ":" + new String(stars));
}
}
Test
printLetterCounts("abaacc");
System.out.println();
printLetterCounts("This is a test of the letter counting logic");
Output
a:***
b:*
c:**
a:*
c:**
e:****
f:*
g:**
h:**
i:****
l:**
n:**
o:***
r:*
s:***
t:*******
u:*

Categories