Occurrences of each letter - java

this is the program that I have to write but I get this error,
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
50
Write a complete program using two arrays, upper and lower to keep the upper
And lower alphabet respectively.
Ask the user to enter string example:
This is a test from Jupiter. Soon you will see who is from
Jupiter!!! May be Dr. D.
Your program should parse the string and keep track of number of alphabet. Both arrays are indexed from 0 to 25. The logical way to do this is to use upper[0] to
Count the number of ‘A’, and upper[1] to count number of ‘B’ and so on. Likewise
For the lower array.
Output should look like:
A: 0 a:2
B: 0 b:0
.
.
.
Z:0 z:0
Code
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
public class Letter {
public static void main(String[] args) {
// this is get results
char[] chars = userEnters();
System.out.println();
System.out.println("Occurrences of each letter are:");
PrintArray(countLow(chars), countUp(chars));
}
public static char[] userEnters() {
String inputX = JOptionPane.showInputDialog("Enter line of text: ");
char[] chars = inputX.toCharArray();
return chars;
}
public static int[] countLow(char[] input) {
int[] counts = new int[26];
for (int i = 0; i < input.length; i++) {
counts[input[i] - 'a']++;
}
return counts;
}
public static int[] countUp(char[] input2) {
int[] countsUp = new int[26];
for (int i = 0; i < input2.length; i++) {
countsUp[input2[i] - 'A']++;
}
return countsUp;
}
public static void PrintArray(int[] counts, int[] countsUp) {
for (int i = 0; i < counts.length; i++) {
System.out.print(counts[i] + " " + (char) ('a' + i) + " ");
System.out.print(countsUp[i] + " " + (char) ('A' + i) + "\n");
}
}
}

If you enter a character that is not a large cap, countUp will throw an exception and if you enter a character that is not a small cap, countLow will throw an exception.
Example: if you call countLow on a A, you calculate 'A' - 'a' which returns -32 and a negative index is not allowed.
You need to review your logic and call either countLow or countUp depending on the case of the letter and filter invalid characters out.
Or refactor the whole thing and use a char[52] for example where you hold both small and large caps.

I Hope you don't mind I did refactor your code a bit.
Please have a look at this alterantive solution to your problem and then read the comments at the bottom of the answer.
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.swing.JOptionPane;
public class LetterCounter {
//Hash maps don't allow duplication.
//The letter will be the Key and the repetitions the value(Your goal!)
private Map<Character, Integer> resultsMap = new HashMap<Character, Integer>();
public static void main(String[] args) {
LetterCounter letterCounter = new LetterCounter();
letterCounter.fillMap();
letterCounter.showMapContents();
}
private void showMapContents() {
for (Entry<Character, Integer> entry : resultsMap.entrySet())
{
System.out.println("'" + entry.getKey() + "' - " + entry.getValue() + " times");
}
}
private void fillMap() {
char[] userInputAsArray = getUserInputAsLetterArray();
for (int currentLetter = 0; currentLetter < userInputAsArray.length; currentLetter++) {
int count = getOccurences(userInputAsArray[currentLetter],userInputAsArray);
resultsMap.put(userInputAsArray[currentLetter], count);
}
}
private int getOccurences(int letter, char[] userInputAsArray) {
int counter = 0;
for (int currentIndex = 0; currentIndex < userInputAsArray.length; currentIndex++) {
if(userInputAsArray[currentIndex] == letter)
counter++;
}
return counter;
}
public char[] getUserInputAsLetterArray() {
String userInput = JOptionPane.showInputDialog("Enter line of text: ");
char[] chars = userInput.toCharArray();
return chars;
}
}
Whenever you want to do an exercise where you need to manipulate data, you should pick the best data structure for the job. In your case, I think the hash map could be interesting because it avoids duplicates and will do a big part of the job for you. Find a very good cheat sheet in this link: http://www.janeve.me/articles/which-java-collection-to-use
I noticed that you used a lot static and that is not a very Object Oriented thing to do. As an alternative, when you want to just on the run do some quick examples like this one, you can just initialize the class inside itself.
I hope this was useful.

You should probably consider moving from arrays to a more complex and powerful data structure like Map<Character,Integer>.
With that data structure the code you need would look something like
public Map<Character,Integer> countOccurrencies(String inputString){
Map<Character,Integer> occurrencies = new HashMap<Character,Integer>();
for(Character c : inputString){
if(occurrencies.containsKey(c)){
occurrencies.put(c, occurrencies.containsKey(c) + 1);
} else {
occurrencies.put(c, 1);
}
}
return occurrencies;
}

Answer in java:
Here, countOfOccurances("pppggggkkkkpgaaaa") gives you count of occurrences of each character from a String
public static void countOfOccurances(String mainStr)
{
String temp = "";
for (int i = 0 ; i < mainStr.length();i++)
{
CharSequence ch = String.valueOf(mainStr.charAt(i));
temp=mainStr.replace(ch, "");
int count = (mainStr.length()-temp.length());
System.out.println(ch+" = "+count);
mainStr = temp;
i = -1;
}
}
Output of method:
p = 4
g = 5
k = 4
a = 4

Related

How to split a string in format AB123 --> AB 123? Java

I have a string in format AB123. I want to split it between the AB and 123 so AB123 becomes AB 123. The contents of the string can differ but the format stays the same. Is there a way to do this?
Following up with the latest information you provided (2 letters then 3 numbers):
myString.subString(0, 2) + " " + myString.subString(2)
What this does: you split your input string myString at the 2nd character and append a space at this position.
Explanation: \D represents non-digit and \d represents a digit in a regular expression and I used ternary operation in the regex to split charter to the number.
String string = "AB123";
String[] split = string.split("(?<=\\D)(?=\\d)");
System.out.println(split[0]+" "+split[1]);
Try
String a = "abcd1234";
int i;
for(i = 0; i < a.length(); i++){
char c = a.charAt(i);
if( '0' <= c && c <= '9' )
break;
}
String alphaPart = a.substring(0, i);
String numberPart = a.substring(i);
Hope this helps
Although I would personally use the method provided in #RakeshMothukur's answer, since it also works when the letter or digit counts increase/decrease later on, I wanted to provide an additional method to insert the space between the two letters and three digits:
String str = "AB123";
StringBuilder sb = new StringBuilder(str);
sb.insert(2, " "); // Insert a space at 0-based index 2; a.k.a. after the first 2 characters
String result = sb.toString(); // Convert the StringBuilder back to a String
Try it online.
Here you go. I wrote it in very simple way to make things clear.
What it does is : After it takes user input, it converts the string into Char array and it checks single character if its INT or non INT.
In each iteration it compares the data type with the prev character and prints accordingly.
Alternate Solutions
1) Using ASCII range (difficulty = easy)
2) Override a method and check 2 variables at a time. (difficulty = Intermediate)
import org.omg.CORBA.INTERNAL;
import java.io.InputStreamReader;
import java.util.*;
import java.io.BufferedReader;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char[] s = br.readLine().toCharArray();
int prevflag, flag = 0;
for (int i = 0; i < s.length; i++) {
int a = Character.getNumericValue(s[i]);
String b = String.valueOf(s[i]);
prevflag = flag;
flag = checktype(a, b);
if ((prevflag == flag) || (i == 0))
System.out.print(s[i]);
else
System.out.print(" " + s[i]);
}
}
public static int checktype(int x, String y) {
int flag = 0;
if (String.valueOf(x).equals(y))
flag = 1; // INT
else
flag = 2; // non INT
return flag;
}
}
I was waiting for a compile to finish before heading out, so threw together a slightly over-engineered example with basic error checking and a test.
import java.text.ParseException;
import java.util.LinkedList;
public class Main {
static public class ParsedData {
public final String prefix;
public final Integer number;
public ParsedData(String _prefix, Integer _number) {
prefix = _prefix;
number = _number;
}
#Override
public String toString() {
return prefix + "\t" + number.toString();
}
}
static final String TEST_DATA[] = {"AB123", "JX7272", "FX402", "ADF123", "JD3Q2", "QB778"};
public static void main(String[] args) {
parseDataArray(TEST_DATA);
}
public static ParsedData[] parseDataArray(String[] inputs) {
LinkedList<ParsedData> results = new LinkedList<ParsedData>();
for (String s : TEST_DATA) {
try {
System.out.println("Parsing: " + s);
if (s.length() != 5) throw new ParseException("Input Length incorrect: " + s.length(), 0);
String _prefix = s.substring(0, 2);
Integer _num = Integer.parseInt(s.substring(2));
results.add(new ParsedData(_prefix, _num));
} catch (ParseException | NumberFormatException e) {
System.out.printf("\"%s\", %s\n", s, e.toString());
}
}
return results.toArray(new ParsedData[results.size()]);
}
}

How to count the occurrence of each letter of the alphabet from a text file in Java?

I'm very new to Java and I'm struggling with my first assignment. The assignment is to scan in a text file (para1.txt) and to read through it and count how many times each letter appears.
(So, it should output something like a-57, b-21, c-12, etc.)
I feel like I'm very close to the answer, however, I'm having a little trouble actually counting the characters as they appear. Currently, my code prints "17" for all the letters, as there are 17 lines in the para1.txt file.
Here is my code so far:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class LetterCounter {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("src/para1.txt"));
int[] count = new int[26];
while (input.hasNextLine()) {
String answer = input.nextLine();
answer = answer.toLowerCase();
char[] characters = answer.toCharArray();
for (int i = 0; i < 26; i++) {
count[i]++;
}
}
for (int i = 0; i < 26; i++) {
StdOut.print((char) (i + 'a'));
StdOut.println(": " + count[i]);
}
}
}
I think you want to take the actual letters and maybe check if you actually have a letter(and not a blank or a number).
public class LetterCounter {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("src/para1.txt"));
int[] count = new int[26];
while (input.hasNextLine()) {
String answer = input.nextLine();
answer = answer.toLowerCase();
char[] characters = answer.toCharArray();
/// change here!
for (int i = 0; i< characters.length ; i++) {
if((characters[i] >='a') && (characters[i]<='z')) {
count[characters[i] -'a' ]++;
}
}
/// change ends.
}
for (int i = 0; i < 26; i++) {
StdOut.print((char) (i + 'a'));
StdOut.println(": " + count[i]);
}
}
}
In your loop, you just increment every index of the count Array:
for (int i = 0; i < 26; i++) {
count[i]++;
}
Instead what you can do is iterate over the characters Array, and increment the index at the char - 'a', to get the correct index:
for(char c : characters) {
count[c - 'a']++;
}
The only issue with this is that if there are any non alphabetic characters, this will throw an index out of bounds error. You may want to ensure it is in range:
int index = c - 'a';
if(index > 25 || index < 0) {
System.out.println("Invalid character");
} else {
//process like normal
}
Create a hashmap with character as key and count(Integer) as value.Hashmap stores key-value pairs,where key will be unique and
put() method is used to insert specific key and value into hashmap.
public class CharCount {
public static void main(String[] args) {
File f1 = new File("file-path");
HashMap<Character, Integer> charMap = new HashMap<Character, Integer>();
try {
Scanner in = new Scanner(f1);
while(in.hasNext()) {
String inputString = in.nextLine();
inputString = inputString.replace(" ", "");
char[] strArray = inputString.toCharArray();
for (char c : strArray) {
if (charMap.containsKey(c)) {
// If character is present in charMap, incrementing it's count by 1
charMap.put(c, charMap.get(c) + 1);
} else {
// If char is not present in charMap ,
// putting this character to charMap with 1 as it's value
charMap.put(c, 1);
}
}
}
// Printing the charMap
System.out.println(charMap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Maybe you're not supposed to know maps yet but one simple solution would be to use one.
Something like this
HashMap<Character, Integer> chars = new HashMap<>();
for(int i = 0; i < characters.length; i++){
if(chars.get(characters[i]) == null){
chars.put(characters[i], 1);
} else {
int num = chars.get(characters[i]);
chars.put(characters[i], num+1);
}
}
for(Character c : chars.keyset()){
print(c + " :" + chars.get(c));
}
Might be some syntax errors, wrote it here

Java cutting string pairs

So here I have a string from 3200 characters I have to find the pair with most space between them I already have the code to find the pair, but then I have to remove the first char of the pair and move the second at the end of the string and do this things till it's not possible to so. Here is what I've done so far
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class StringPairs {
public static void main(String[] args) {
String inputString = readInputString();
printIdenticalSymbols(inputString);
}
private static String readInputString() {
Scanner in = new Scanner(System.in);
String inputString = in.nextLine();
in.close();
return inputString;
}
private static void printIdenticalSymbols(String inputString) {
Map<Character, Integer> symbolsMap = new HashMap<Character, Integer>();
char longestChar = ' ';
int longestDiff = -1;
int firstIndex = -1;
int lastIndex = -1;
int firstOccurenceOfLastIdentical = -1;
for (int i = 0; i < inputString.length(); i++) {
char currentCharacter = inputString.charAt(i);
if (!symbolsMap.containsKey(currentCharacter)) {
symbolsMap.put(currentCharacter, i);
continue;
}
int firstOccurenceIndex = symbolsMap.get(currentCharacter);
if (firstOccurenceIndex < firstOccurenceOfLastIdentical) {
symbolsMap.put(currentCharacter, i);
continue;
}
int currentIdenticalLength = i - firstOccurenceIndex;
if (currentIdenticalLength > longestDiff) {
longestChar = currentCharacter;
longestDiff = currentIdenticalLength;
firstIndex = firstOccurenceIndex;
lastIndex = i;
}
firstOccurenceOfLastIdentical = firstOccurenceIndex;
symbolsMap.put(currentCharacter, i);
}
System.out.println(longestChar + " - " + firstIndex + ":" + lastIndex);
}
}
example input:
brtba
output: b:space between them(it already does this) and rtab if the string is bigger do this thing till it's not possible to do so.
It suspiciously looks like homework to me.
Anyway, you should look into String manipulation functions, especially String.substring(begin,end). To make a loop, look into the while loop. Note that you don't handle yet the case where there is no pair.
This being said, I don't understand the function of the test:
(firstOccurenceIndex < firstOccurenceOfLastIdentical).

How can I check character occurrence in a string?

My Question is-
Input is string. Return true if the String has exactly 1 character that appears twice in the string, 0 character that appear thrice in the string, and at least 1 character that appear four or more times in the string. There is a problem in my code and I am unable to find out the problem.
public class CheckCharacterOccurence {
static String testcase1 = "jjiiiiyy";
public static void main(String[] args) {
CheckCharacterOccurence testInstance = new CheckCharacterOccurence();
boolean result = testInstance.checkCharacterOccurence(testcase1);
System.out.println(result);
}
public boolean checkCharacterOccurence(String str) {
char ch=' ';
char ch1=' ';
int temp=0;
int temp1=0;
int temp2=0;
int count=0;
for(int i=0;i<str.length();i++){
ch=str.charAt(i);
for(int j=i;j<str.length();j++){
if(str.charAt(i)==str.charAt(j)){
ch1=str.charAt(i);
count++;
}
}
System.out.println(count);
if(count==2&&ch!=ch1){
temp++;
}
if(count==3&&ch!=ch1){
temp1++;
}
if(count>=4){
temp2++;
}
count=0;
}
if(temp==1&&temp1==0&&temp2>=1){
return true;
}
return false;
}
}
I would suggest using a map
For all characters in string, increment map[that_char]
At last iterate over map to find how many times each character appeared.
Alternatively you can use array also to keep count.
Something like
int [] ctr = new int[256]
ctr = all zeroes
for (ch : string)
ctr[ch]++
mxocc = 0
maxch = 'a'
for(ch = a, b, c, d, e...)
if(ctr[ch] > maxocc) maxocc = ctr[ch] and maxch = ch
Output require info
hey you can figure out the problem ... atleast i can give to some extend same code , you can check it and try to solve your problem... This program finds the pattern in the string, now you can go through this program, and try to solve ur problem in your program by your own self.and try to do it by your own then only ur coding skills will get improved.and vote this answer if u fing it really helpful
#include<stdio.h>
#include<string.h>
int occur(char[],char[]);
int occur(char sent[],char pattern[])
{
int count=0;
for(int i=0,j=i;sent[i]!='\0';)
{
if(sent[i+j]==pattern[j]&&pattern[j]!='\0')
{
j++;
}
else if(j==strlen(pattern))
{
count++;
i=i+j;
j=0;
}
else
{
i++;
j=0;
}
}
return count;
}
int main()
{
char sent[] = "aabaabaaabbbabababddfggaabbbasab";
char pattern[] = "aba";
int result = occur(sent,pattern);
printf("\nNo of Occurrences --- > %d",result);
return 0;
}
You should simplify your code. For example there is not need to use those complex for-loops, you can use a for-each.
This code finds out the frequency of characters in a string and stores it in a Map.
import java.util.*;
public class CheckCharacterOccurence {
public static void main(String[] args) {
Map<Character, Integer> counting = new HashMap<Character, Integer>();
String testcase1 = "Helloooo";
for(char ch: testcase1.toCharArray()){
Integer freq = counting.get(ch);
counting.put(ch, (freq == null) ? 1 : freq + 1);
}
System.out.println(counting.size() + " distinct characters:");
System.out.println(counting);
}
}

count specific characters in a string (Java)

I have a homework assignment to count specific chars in string.
For example: string = "America"
The output should be = a appear 2 times, m appear 1 time, e appear 1 time, r appear 1 time, i appear 1 time and c appear 1 time
public class switchbobo {
/**
* #param args
*/ // TODO Auto-generated method stub
public static void main(String[] args){
String s = "BUNANA";
String lower = s.toLowerCase();
char[] c = lower.toCharArray(); // converting to a char array
int freq =0, freq2 = 0,freq3 = 0,freq4=0,freq5 = 0;
for(int i = 0; i< c.length;i++) {
if(c[i]=='a') // looking for 'a' only
freq++;
if(c[i]=='b')
freq2++;
if (c[i]=='c') {
freq3++;
}
if (c[i]=='d') {
freq4++;
}
}
System.out.println("Total chars "+c.length);
if (freq > 0) {
System.out.println("Number of 'a' are "+freq);
}
}
}
code above is what I have done, but I think it is not make sense to have 26 variables (one for each letter). Do you guys have alternative result?
Obviously your intuition of having a variable for each letter is correct.
The problem is that you don't have any automated way to do the same work on different variables, you don't have any trivial syntax which helps you doing the same work (counting a single char frequency) for 26 different variables.
So what could you do? I'll hint you toward two solutions:
you can use an array (but you will have to find a way to map character a-z to indices 0-25, which is somehow trivial is you reason about ASCII encoding)
you can use a HashMap<Character, Integer> which is an associative container that, in this situation, allows you to have numbers mapped to specific characters so it perfectly fits your needs
You can use HashMap of Character key and Integer value.
HashMap<Character,Integer>
iterate through the string
-if the character exists in the map get the Integer value and increment it.
-if not then insert it to map and set the integer value for 0
This is a pseudo code and you have to try coding it
I am using a HashMap for the solution.
import java.util.*;
public class Sample2 {
/**
* #param args
*/
public static void main(String[] args)
{
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
String test = "BUNANA";
char[] chars = test.toCharArray();
for(int i=0; i<chars.length;i++)
{
if(!map.containsKey(chars[i]))
{
map.put(chars[i], 1);
}
map.put(chars[i], map.get(chars[i])+1);
}
System.out.println(map.toString());
}
}
Produced Output -
{U=2, A=3, B=2, N=3}
In continuation to Jack's answer the following code could be your solution. It uses the an array to store the frequency of characters.
public class SwitchBobo
{
public static void main(String[] args)
{
String s = "BUNANA";
String lower = s.toLowerCase();
char[] c = lower.toCharArray();
int[] freq = new int[26];
for(int i = 0; i< c.length;i++)
{
if(c[i] <= 122)
{
if(c[i] >= 97)
{
freq[(c[i]-97)]++;
}
}
}
System.out.println("Total chars " + c.length);
for(int i = 0; i < 26; i++)
{
if(freq[i] != 0)
System.out.println(((char)(i+97)) + "\t" + freq[i]);
}
}
}
It will give the following output:
Total chars 6
a 2
b 1
n 2
u 1
int a[]=new int[26];//default with count as 0
for each chars at string
if (String having uppercase)
a[chars-'A' ]++
if lowercase
then a[chars-'a']++
public class TestCharCount {
public static void main(String args[]) {
String s = "america";
int len = s.length();
char[] c = s.toCharArray();
int ct = 0;
for (int i = 0; i < len; i++) {
ct = 1;
for (int j = i + 1; j < len; j++) {
if (c[i] == ' ')
break;
if (c[i] == c[j]) {
ct++;
c[j] = ' ';
}
}
if (c[i] != ' ')
System.out.println("number of occurance(s) of " + c[i] + ":"
+ ct);
}
}
}
maybe you can use this
public static int CountInstanceOfChar(String text, char character ) {
char[] listOfChars = text.toCharArray();
int total = 0 ;
for(int charIndex = 0 ; charIndex < listOfChars.length ; charIndex++)
if(listOfChars[charIndex] == character)
total++;
return total;
}
for example:
String text = "america";
char charToFind = 'a';
System.out.println(charToFind +" appear " + CountInstanceOfChar(text,charToFind) +" times");
Count char 'l' in the string.
String test = "Hello";
int count=0;
for(int i=0;i<test.length();i++){
if(test.charAt(i)== 'l'){
count++;
}
}
or
int count= StringUtils.countMatches("Hello", "l");

Categories

Resources