Count each character - java

I'm trying to count each char in string for example:
Sample input: abababx
Sample output :
a appears 3 times
b appears 3 times
x appears 1 time
Here is what I've done :
String s = input.nextLine();
//Invoke the count method to count each letter
int[] counts = countLetters(s.toLowerCase());
for (int i = 0; i < counts.length; i++) {
if (counts[i] != 0)
System.out.println((char)('a' - i) + " appears " +
counts[i] + ((counts[i] == 1 ? " time" : " times")));
}
private static int[] countLetters(String s) {
int[] counts = new int[26];
for (int i = 0; i < s.length(); i++) {
if (Character.isLetter(s.charAt(i)))
counts[s.charAt(i) - 'a']++;
}
return counts;
}
I'm getting:
a appears 3 times
` appears 3 times
J appears 1 time

Related

How to determine how many times a character is repeated in a string?

I am having some trouble with writing a method that when prompted with a number returns how many times each value is repeated. For example, if the number 7846597 is entered the method would return:
0 - 0
1 - 0
2 - 0
3 - 0
4 - 1
5 - 1
6 - 1
7 - 2
8 - 1
9 - 1
I know this would be most easily done with a loop, but I am not sure how to write the actual code. I also know that I need to convert the number value I get as an input into a string so I can use char methods.
This is my attempt:
public double countOccurences(int num)
{
String str = num + "";
int goneThrough = 0;
int count0 = 0;
int count1 = 0;
int count2 = 0;
int count3 = 0;
int count4 = 0;
int count5 = 0;
int count6 = 0;
int count7 = 0;
int count8 = 0;
int count9 = 0;
while(goneThrough <= str.length())
{
int value = 0;
if(value >= 10){
value = value * 0;
}
if(str.charAt(0) == 0)
count0++;
if(str.charAt(0) = 1)
count1++;
}
return count0;
return count1;
return count2;
return count3;
return count4;
return count5;
return count6;
return count7;
return count8;
return count9;
}
countOccurences(int num) should return the number of occurrences of each digit as int[10].
static int[] countOccurences(int num) {
int[] result = new int[10];
for ( ; num > 0; num /= 10)
++result[num % 10];
return result;
}
public static void main(String[] args) {
int input = 7846597;
int[] output = countOccurences(input);
for (int i = 0; i < 10; ++i)
System.out.println(i + " - " + output[i]);
}
output:
0 - 0
1 - 0
2 - 0
3 - 0
4 - 1
5 - 1
6 - 1
7 - 2
8 - 1
9 - 1
This is my code where I used HashTable and stored number as string and count as value. This is optimized code where time complexity is O(n).
// code
import java.util.*;
class Main {
public static void main(String args[]) {
String number = "7846597";
Hashtable<String, Integer> result = new Hashtable<String, Integer>();
for(int i=0; i<number.length(); i++){
String current = "" + number.charAt(i);
if(result.contains(current)) {
int val = result.get(current);
result.put(current, ++val);
} else {
result.put(current, 1);
}
}
System.out.print(result);
}
}
Using int array of size 10 and increment value at index that maps to digit of 0-9.
public static void digitFrequencies(int number) {
int[] arr = new int[10];
for (char ch : String.valueOf(number).toCharArray()) {
int digit = Character.digit(ch, 10);
arr[digit] = arr[digit] + 1;
}
for (int i = 0; i < arr.length; i++) {
System.out.print(i + " - " + arr[i] + " ");
}
}

Running sum of an ArrayList with 2 possible operations

I am trying to create a program insert two possible operations (* and +) in between inputed numbers and keep track of the total. The program simply reads from left to right so therefor do not apply BEDMAS
For instance if I inputed: 1 2 3
The output would be 1 + 2 + 3 -> Sum = 6
Or output would be 1 + 2 * 3 -> Sum = 9
Or output would be 1 * 2 + 3 -> Sum = 5
Etc
I am having difficulty because my program continues to try to numbers.remove() from an empty ArrayList(numbers).
public static void calculate(ArrayList<Integer> numbers, int target){
ArrayList<Integer> temp_array = new ArrayList<Integer>(numbers);
int sum = 0;
int n = (numbers.size() - 1);
System.out.println("This is where we calcutale L");
for (int i = 0; i < Math.pow(2, n); i++) {
String bin = Integer.toBinaryString(i);
while (bin.length() < n)
bin = "0" + bin;
char[] chars = bin.toCharArray();
char[] charArray = new char[n];
while(charArrayCount < Math.pow(2,n)){
for (int j = 0; j < chars.length; j++) {
charArray[j] = chars[j] == '0' ? '+' : '*';
}
for(char c : charArray){
int current = numbers.get(0);
if (c == '+'){
sum = sum + current;
}
numbers.remove(0);
System.out.println(sum);
}
numbers = temp_array;
sum = 0;
}
}
}

How to get out of for loop at the end of the loop and enter in a new without making the sum

Here is my code. I have to count the frequency of letters in my text.
I got as output:
a 21
b 28(should be 7)
c 34(should be 6)
I think my problem is it makes the sum and i dont want it.
int[] alphabetArray = new int[26];
// char varA = 'a';
alphabetArray[0] = A;``
int count = 0;
for (int i = 0; i < text.length; i++) {
if (text[i] == A) {
count++;
}
}
System.out.println((char) alphabetArray[0] + " kommt " + count + " Mal");
alphabetArray[1] = B;
for (int i = 0; i < text.length; i++) {
if (text[i] == B) {
count++;
}
}
System.out.println((char) alphabetArray[1] + " kommt " + count + " Mal");
alphabetArray[2] = C;
for (int i = 0; i < text.length; i++) {
if (text[i] == C) {
count++;
}
}
System.out.println((char) alphabetArray[2] + " kommt " + count + " Mal");
return null;
Although you could fix your problem by zeroing out the count after printing, your program would not be ideal with the loop itself repeated three times. When you see a pattern like this, it's an indication that you need another loop.
Make a loop outside your current loop going through the letters from 'A' to 'Z'. Since letters' code points in UNICODE are consecutive, you can find the index of a letter by subtracting 'A' from it:
for (char letter = 'A' ; letter <= 'Z' ; letter++) {
int letterIndex = letter - 'A';
for (int i = 0; i < text.length; i++) {
if (text[i] == letter) {
alphabetArray[letterIndex]++;
}
}
}
Note that since you are accumulating counts for all letters, you do not need a separate count variable, because alphabetArray[letterIndex] replaces it. If you want to print letter frequency as you go, print alphabetArray[letterIndex] after the nested loop.
You initialized count=0 once and you are increasing it without re-initalizing it to 0.
int[] alphabetArray = new int[26];
// char varA = 'a';
alphabetArray[0] = A;``
int count = 0;
for (int i = 0; i < text.length; i++) {
if (text[i] == A) {
count++;
}
}
System.out.println((char) alphabetArray[0] + " kommt " + count + " Mal");
alphabetArray[1] = B;
count=0;
for (int i = 0; i < text.length; i++) {
if (text[i] == B) {
count++;
}
}
System.out.println((char) alphabetArray[1] + " kommt " + count + " Mal");
alphabetArray[2] = C;
count=0;
for (int i = 0; i < text.length; i++) {
if (text[i] == C) {
count++;
}
}
System.out.println((char) alphabetArray[2] + " kommt " + count + " Mal");
return null;

Java: Count occurrence of letters in a String

I am trying to write a program that counts the occurrence of letters in a string. For example, if the user inputs "Java", it will display "j: 1 a: 2 v:1". However, there seems to be something wrong with my program, and when I input the word java this is what it shows "j: 0 a: 1 v: 0"
Scanner myScanner = new Scanner(System.in);
String s = myScanner.nextLine();
int i = 0;
int j = 0;
int cnt = 0;
int length = s.length();
char ch;
for (i = 0; i < length; i++) {
ch = s.charAt(i);
if (s.indexOf(ch) < i)
continue;
for (j = (i + 1); j < length; j++) {
if (s.charAt(j) == ch)
cnt++;
}
System.out.println(ch + ": " + cnt);
cnt = 0;
}
Your desired output:
Enter your String: Mascarena
M: 1
a: 3
s: 1
c: 1
r: 1
e: 1
n: 1
Error in your code:
for (j = (i + 1); j < length; j++) { //It is omitting the first letter and searches the remaining
if (s.charAt(j) == ch)
cnt++;
}
Rectified:
for (j = 0; j < length; j++) { //For a specific letter searches the whole string.
if (s.charAt(j) == ch)
cnt++;
}
Your 2nd for-loop is not searching the entire word for each letter.
For example, when searching for j it is only looking at ava because it starts at i + 1 which is
(0 + 1) = 1
this a in the string java as j would be index at 0. Change
for (j = (i + 1)..)
to
(j = 0..)
public static String numberOfOccurence(String data) {
String result = "";
while (!data.isEmpty()) {
result += String.valueOf(data.charAt(0))+ StringUtils.countOccurrencesOf(data, String.valueOf(data.charAt(0)));
data = data.replaceAll(String.valueOf(data.charAt(0)), "");
}
return result;
}
input: aabacbd
output: a3b2c1d1

Array java help needed

I have this program that takes user input and displays the number of times each integer is entered. I pretty much have it down pat but need another loop to omit the shown occurrence of 0. In other words any number with 0 in it cannot be read, also for some reason i am getting two outputs from the same number in my program. For example, if I enter 3,3 I will get 3 occurs 1 time and 3 occurs 2 times as output. The 2 times one being correct and the first one being incorrect.
public class Six_Three {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("enter integers between 1 and 100: ");
int[] num = new int[100];
int data = input.nextInt();
while ((data = input.nextInt()) != 0) {
num[data]++;
}
for (int i = 1; i < 100; ++i) {
if (num[i] > 0)
System.out.println(i + " occurs " + num[i] + " times ");
}
}
You need two separate loops: the first to gather the information, and the second to print the results:
int data = 0;
while ((data = input.nextInt()) != 0)
{
num[data]++;
}
for (int i = 0; i < 100; ++i)
{
if (num[i] != 0) { /* print num[i] */ }
}
Just loop over the num array after your while loop to print the counts.
for (int index = 0; index < num.length; index++) {
if (num[index] != 0)
System.out.println(data + " occurs " + num[data] + " time(s).");
}
You are printing an output every time an integer is read. Your program is behaving as expected.
To get what you want, you need to scan all the input before you produce any output.
Try this instead:
while (data != 0){
data = input.nextInt();
num[data]++;
}
for (int i = 1; i < 100; ++i) { // your version is 0...99, else array index out of bounds
if (num[i] > 0)
System.out.println(i + " occurs " + num[i] + " times ");
}
The way you write it the last number has to be 0 to make the scanning stop. It might be a good idea to check if there's another int available and use that as a condition for the scanning loop. That way your program can accept any integer.
while (input.hasNextInt()){
num[input.nextInt()]++;
}
it's so simple
int data = 0;
int[] num = new int[100];
int i = 0;
while (i < num.length) {
if ((data = input.nextInt()) == 0)
break;
num[i] = data;
i++;
}
for (i = 0; i < 100; ++i) {
int times = 0;
if (num[i] != 0) {
for (int j = 0; j < 100; j++) {
if (num[j] == 0) {
break;
} else if (num[i] == num[j]) {
times++;
}
}
System.out.println(num[i] + " occurs " + times + " times ");
} else {
break;
}
}

Categories