Java - Histogram program - java

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.

Related

how to print count of each character in a string using 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).

Method to check if the string contains certain elements that accepts a parameter String

I am a student and kind of new to Java. For my homework I have to:
Ask the user to input a number (at least 7) using a do while loop.
Using a for loop I am required to ask the user to input that number of words.
Then I have to check if one of the words fulfills the given conditions:
The word must:
Start with an uppercase letter
End with a number
Contain the word "cse".
I am asked to create a method inside some code homework that does a specific task, the method should check all the required conditions, the name of the method should be countTest and it accepts the String as a parameter.
I will show you my code but I don't know how to create this specific method.
Output format
System.out.println("There as a total number of words " + count + " and
the ones that fulfill the condition are: " + condition);
The problem is, I dont know how to create the method or constructor or whatever it is called that calls all of the 3 methods inside it, and then connect that particular method to the main method!
I hope you guys can understand I am new to this, thank you in advance!
public class D6_6 {
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do{
if(number<7){
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while(number<7);
sc.nextLine();
String str;
for(int i =0; i<number; i++){
System.out.println("Type a word");
str = sc.nextLine();
count++;
}
}
public boolean countTest(String str) {
}```
To check if the word start with an uppercase:
You can do that by first selecting the character you want to check by str.charAt(0). This will return a char that is the first letter of the input str.
To check if this char is an uppercase letter, you can easily use char.isUppercase(). This will return a boolean. You have to replace char by the name of the variable were you put the char of str.charAt(0) in.
To check if the last character is a number:
You can do that again by first selecting the last character by str.charAt(str.length()-1), were string.length-1 is the number of the last character.
To check if this character is a number, you can use the ascii table. Every character has it's own number. So if you want to check if your character is between 0 and 9, you can use char >= 48 || char <= 57 (look up in the ascii table). Again, char is the name of the variable were you put the char of str.charAt(str.length()-1) in.
To check if the word contains "cse":
There is a very easy method for that: str.contains("cse") will return a boolean that is true when "cse" is in the word and false when the word does not contain "cse".
I hope it is clear for you now!
I think I did it, thank you guys very much, I appreciate it!
public class D6_6 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do {
if (number < 7) {
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while (number < 7);
sc.nextLine();
String str;
for (int i = 0; i < number; i++) {
System.out.println("Type a word");
str = sc.nextLine();
count++;
if((countTest(str))){
condition++;
}
}
if(count == 0){
System.out.println("No words typed");
} else {
System.out.println("Total number of words typed: " + count + ", which fulfill the condition: "+ condition);
}
}
public static boolean countTest(String str) {
return Character.isUpperCase(str.charAt(0)) && str.charAt(str.length() - 1) >= 48 || str.charAt(str.length() - 1) <= 57 || str.contains("cse");
}
}```

Read in a sentence and print out only words that have the same letter repeated 3 or more times in a row

I wanted to make a program in which only repeats words that has 3 of the same letters back to back. eg the mooonkey raaan through the mounnntains. the program should only repeat mooonkey, raaan
public class Triplets2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
String [] sentence = in.split(" ");
for (int i = 0; i < sentence.length; i++) {
char [] word = sentence[i].toCharArray();
int counter =0;
for (int s = 0; s < word.length; s++) {
char letter = word[s];
for (int x = 0; x<word.length; x++) {
if (letter == word[x]) {
counter++;
}
else {
counter = 0;
}
}
}
if (counter >=3) {
System.out.print(sentence[i] + ", ");
}
}
}
the program instead just repeats nothing.
Your code is almost correct, the only logical error you made is inside your inner loop you keep resetting your counter variable as soon as you find a letter that is different:
if (letter == word[x]) {
counter++;
} else {
counter = 0;
}
So when you iterate over a word like "raaan" your counter will reset when it reaches the very end of the String, because "n" only exists once.
What this means is that you will only be able to detect words that have 3 consecutive letters at the very end (like "Hooo").
The solution is simple:
Once you found 3 consecutive letters in a word you can just stop iterating and checking the rest of your word. At that point you already know that it fits your criteria:
if (letter == word[x]) {
counter++;
if(counter >= 3) break; // stop inner loop checking once we found 3 letters
} else {
counter = 0;
}
Since you are looking for consecutive letters you want to start at char i and then compare the char at i to char at i+1 and at i+2. If they are all equal then we have a match and can continue.
You can simplify the whole function such as:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
List<String> tripleLetter = new ArrayList<>();
for (String s : in.split(" ")) {
char[] word = s.toCharArray();
for (int i = 0; i < word.length - 2; i++) {
if ((word[i] == word[i+1]) && (word[i] == word[i+2])) {
tripleLetter.add(s);
break;
}
}
}
System.out.println(tripleLetter.stream().collect(Collectors.joining(", ")));
}
Allow me to suggest a solution that differs slightly from yours and doesn't use a counter.
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
String[] sentence = in.split(" ");
for (int i = 0; i < sentence.length; i++) {
char[] word = sentence[i].toCharArray();
for (int s = 0; s < word.length - 2; s++) {
if (word[s] == word[s + 1] && word[s] == word[s + 2]) {
System.out.print(sentence[i] + ", ");
break;
}
}
}
Check whether the current letter, in the current word, is the same as the next letter and the same as the letter after the next letter. If the condition holds, then print the current word and proceed to the next word in the sentence.
Well, if you're just looking for a shorter version of doing this then try this.
first, split the sentence on one or more white space characters (you should be doing that regardless).
stream the array and filter on a single character, followed by the same two characters via a back reference to the capture group (see regular expressions for that).
And print them.
String str =
"Thiiis is aaaa tesssst of finding worrrrds with more than threeeeee letteeeeers";
Arrays.stream(str.split("\\s+"))
.filter(s -> s.matches(".*(.)\\1\\1.*"))
.forEach(System.out::println);
Prints
Thiiis
aaaa
tesssst
worrrrds
threeeeee
letteeeeers

Counting words with minimum length in java

Write your code in the file WordCount.java. Your code should go into a method with the following signature. You may write your own main method to test your code. The graders will ignore your main method:
public static int countWords(String original, int minLength){}
Your method should count the number of words in the sentence that meet or exceed minLength (in letters). For example, if the minimum length given is 4, your program should only count words that are at least 4 letters long.
Words will be separated by one or more spaces. Non-letter characters (spaces, punctuation, digits, etc.) may be present, but should not count towards the length of words.
Hint: write a method that counts the number of letters (and ignores punctuation) in a string that holds a single word without spaces. In your countWords method, break the input string up into words and send each one to your method.
I am trying to get the minimum length of the word in the code, without it counting punctuation marks and such. how do i do that? Also, I will get rid of the main method as it will be added automatically. How do i make the program automatically add a space after the last word?
public class WordCounts
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = in.nextLine();
System.out.println("minLength");
int minLength=in.nextInt();
System.out.print("Your sentence has " + countWords(sentence,minLength)+ " words.");
}
public static int countWords(String str, int minLength)
{
int count = 0;
int c=0;
for (int i=0;i<=str.length()-1;i++)
{
if (str.charAt(i) != ' ')
{
if(str.charAt(i)>='a' && str.charAt(i)<='z') //to check only for alphabets.
c++;
}
if(c>=minLength)
{
count++;
c=0;
}
}
return count;
}
}
You have to pass minLength as a parameter to the countWords function. That way, you will be able to access this variable in the countWords function. You will also want to loop through the string character by character and keep track of how many letters you have seen, call it "numLetters". Check if the character is present in the string "aAbBcC....yYzZ" to ensure it is a letter, and if it is present, then add 1 to "numLetters". If you reach the end of the input or reach a space, then check if numLetters is greater than minLength, and if so, add 1 to count. Reset numLetters to 0 and keep going until you reach the end of the string.
e.g. to get the character:
for (int i = 0; i < str.length(); i++){
char c = str.charAt(i);
}
I think I understood your problem statement correctly. Correct me if I am wrong.
You want to check that the length of entered string should be greater than the minimum entered length. For that you need to pass the minLength variable to the method countWords. And then you are checking that the character is valid or not using if (str.charAt(i) == ' ' && str.charAt(i+1)!=' ')
Updated method
public static int countWords(String str, int minLength)
{
int count = 1;
for (int i=0;i<=str.length()-1;i++)
{
if (str.charAt(i) == ' ' && str.charAt(i+1)!=' ' && str.length()>=minLength)
{
count++;
}
}
return count;
}
In your main method, take input using Scanner
int minLength=in.nextInt();
Your function should be like this:
Also you have to pass the value of minLength to function You cannot access minLength outside main.
public static int countWords(String str,int minLength)
{
int count = 0;int c=0;
for (int i=0;i<str.length();i++)
{
if (str.charAt(i) != ' ')
{
if(str.charAt(i)>='a' && str.charAt(i)<='z')
c++;
continue;
}
if(c>=minLength)
{
count++;
}
c=0;
}
if(c>=minLength)
return count+1;
else
return count;
}
}

Finding duplicated or repeated character in a string and return the number of repeation in Java

I have created a Java program to find duplicated character in a String and tell how many times this character is duplicated.
I have created two arrays with the same characters, and two for loops that compare the first element of the first array with all characters in the second array,and so as for the second element,
Here is my code:
Scanner console=new Scanner(System.in);
char[] array=console.next().toCharArray();
char[] array2=array;
int count=0;
char m;
for (int i=0; i<array.length; i++) {
for (int j=0; j<array2.length; j++) {
if (array[i]==array2[j]) {
count=count+1;
} // end if
} //end loop inner
if ( count>=2) {
System.out.println(array[i]+" is duplicated "+count+" times!");
} // end 2nd if
count=0;
} //end outer loop
an example of my output is:
aabb
a is duplicated 2 times!
a is duplicated 2 times!
b is duplicated 2 times!
b is duplicated 2 times!
As you can see my problem is that if a character is repeated two times it prints two lines saying its duplicated two times, and i know the reason behind this but i dont know how to solve it!. I dont want to use hashmap, because until now i have only studied if/else, loops, and lately something about arrays, so if your answer lies among this subjects thanks!
You may use an Object (here a String) to keep track of the already encountered characters.
Scanner console=new Scanner(System.in);
char[] array=console.next().toCharArray();
char[] array2=array;
int count=0;
char m;
String memoryString = "";
for (int i=0; i<array.length; i++) {
for (int j=0; j<array2.length; j++) {
if (memoryString.contains(String.valueOf(array[i])) break;
if (array[i]==array2[j]){
count=count+1;
}
} //end loop inner
memoryString+=array[i]
if (count>=2) {
System.out.println(array[i]+" is duplicated "+count+" times!");
}
count=0;
} //end outer loop
you could instead loop through all the possible characters and see how many of them exist in the string (assuming you are ok with using a string instead of an array of characters):
while(!str.isEmpty())
{
int count = 0;
char c = str.charAt(0);
while(str.indexOf(c) != -1)
{
str = str.replaceFirst(String.valueOf(c), "");
count++;
}
System.out.println("number of " + c + " " + count);
}
Edit: do to the backlash against my (poor) assumption and using a 256 limit on the number of chars, i reworked it a bit. hope this is a bit better!
Here is how you could do this (Assuming ASCII charset):
public static void main(String[] args) {
Scanner console=new Scanner(System.in);
char[] array=console.next().toCharArray();
int[] counts = new int[255];
for(char c : array) {
counts[c]++;
}
for(int i = 0; i < 255; i++){
if (counts[i] > 1)
System.out.println("duplicated char: " + (char)i + ", " + counts[i] + "times");
}
}
The logic is:
Create an array of integers to keep track of counts of each input character
Loop through each character in the string and increment the count. The index of counts array will be the ascii value of the character.
Do a one pass through the counts array to figure out which characters have counts more than 2 and print them.

Categories

Resources