Count word length with occurrence - java

I am doing a program to count the length of each word followed by the number of occurrences of that length.
For example:
Enter a String :I love my work
The word count is -
No. of words of length 1 are 1.
No. of words of length 2 are 1.
No. of words of length 4 are 2.
So far I tried this,
import java.util.Scanner;
class Demo{
public static void main(String[] args){
String s;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a String :");
s=sc.nextLine();
String[] arr = s.split(" ");
String str = "";
int [] len = new int[arr.length];
int [] count = new int[arr.length];
int c = 0;
for(int i=0;i<arr.length;i++){
str = arr[i];
len[i] = str.length();
for(int j=0;j<arr.length;j++){
if(str.length() == arr[j].length()){
count[i] = ++c;
}
}
c = 0;
}
for(int i=0;i<len.length;i++){
System.out.println("No. of words of length "+len[i]+" are "+count[i]+".");
}
}
}
There is a problem in my logic and that's why it's output is like this:
Enter a String :I love my work
The word count is -
No. of words of length 1 are 1.
No. of words of length 2 are 1.
No. of words of length 4 are 2.
No. of words of length 4 are 2.
Any suggestion how to fix that or any other simpler way to do it(without using collections, maps).

You can replace array with a Map<Integer,Integer>, It will easiar.
Scanner sc = new Scanner(System.in);
System.out.print("Enter a String :");
String s = sc.nextLine();
String[] arr = s.split(" ");// get the words
Map<Integer, Integer> lengthVsCount=new HashMap<>(); // length vs count
for(String i:arr){ // iterate array
Integer val=lengthVsCount.get(i.length()); // searching count
if(val!=null){ // if count is there
lengthVsCount.put(i.length(),val+1);// increment count by one
}else{ // count not there
lengthVsCount.put(i.length(),1); // add count as one
}
}
for (Map.Entry<Integer,Integer> entry:lengthVsCount.entrySet()) {
System.out.println("No. of words of length " + entry.getKey() + " are " + entry.getValue() + ".");
}

You should use a map:
public static void main(String[] args) {
final String input = "I love my work";
final String[] words = input.split(" ");
final Map<Integer, Integer> occurencesMap = new HashMap<Integer, Integer>();
for (final String word : words) {
final int lenght = word.length();
if (occurencesMap.get(lenght) == null) {
occurencesMap.put(lenght, 1);
} else {
occurencesMap.put(lenght, occurencesMap.get(lenght) + 1);
}
}
System.out.println("The word count is -");
final Iterator<Map.Entry<Integer, Integer>> entries = occurencesMap.entrySet().iterator();
while (entries.hasNext()) {
final Map.Entry<Integer, Integer> entry = entries.next();
System.out.println("No. of words of length " + entry.getKey() + " are " + entry.getValue());
}
}

class Demo{
public static void main(String[] args){
String s;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a String :");
s=sc.nextLine();
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (String str : s.split(" ")) {
int key = str.length();
if (map.containsKey(key)) {
map.put(key, map.get(key)+1);
}
else {
map.put(key, 1);
}
}
Iterator<Integer> iterator = map.keySet().iterator();
while(iterator.hasNext()) {
int key = iterator.next();
System.out.println("No. of words of length " + key + " are " + map.get(key) + ".");
}
}
}

Here,
for(int i=0;i<arr.length;i++){
str = arr[i];
len[i] = str.length();
You should check if len[i] is not a value already in the array. So use
int k;
for(k=0 ; k<i ; k++ )
if( len[i]==len[k] ) //if a match was found
break; //break out of the loop
if(k!=i) //will be true if the break has been executed
{
len[i]=0; //set to 0
continue; //go back to the loop
}
Just after that and use
for(int i=0;i<len.length;i++){
if(len[i]!=0)
System.out.println("No. of words of length "+len[i]+" are "+count[i]+".");
}
When printing the results.

Related

Problem: printing an index, value of index, length index in an array has a loop

import java.util.Scanner;
public class missYou {
public static void main(String[] args) {
System.out.println("Words");
System.out.print("Enter words: ");
Scanner input = new Scanner(System.in);
String word = input.nextLine();
String[] parts = word.split(" ");
String max = parts[0];
int max_box; int parts_L = parts.length;
int max_L; int i;
for (i = 1; i < parts_L; i++) {
if (parts[i].length() > max.length()) {
max = parts[i];
max_box = i;
max_L = parts[i].length();
}
}
/* the problem occurs in the next line where it does not print the max value,
and it considers max_L without a value which I did give it a value in the
loop and the I value should be the same as the index of the longest
string but it gives me the last index in the array */
System.out.print("The longest word is " + max + " contain " +
max_L + " letters, in box " + i);
input.close();
}
}
The problem is that you are mixing i with max_box. The following should work as you expect:
public class missYou {
public static void main(String[] args) {
System.out.println("Words");
System.out.print("Enter words: ");
Scanner input = new Scanner(System.in);
String word = input.nextLine();
String[] parts = word.split(" ");
String longestWord = parts[0];
int longestWordSize = longestWord.length();
int longestWordLocation = 0;
for (int i = 1; i < parts.length; i++) {
if (parts[i].length() > longestWordSize) {
longestWord = parts[i];
longestWordLocation = i;
longestWordSize = longestWord.length();
}
}
System.out.print("The longest word is " + longestWord + " contain " +
longestWordSize + " letters, in box " + longestWordLocation);
input.close();
}
}
Additionally, try to be explicit when naming your variables, max_L and max_box are not very good names because they are hard to understand.

I want to display the occurrence of a character in string. How can I improve my code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to create a program that will display the number of occurrences of a character in a string and also count them. Right now the code just counts the characters.
I want to make the following changes:
1) How do I make this program only count one type of a character, like a or c in a string I love ice cream.
2) How do I also print the character in a string, let's say there are two d my program will then display 2 d first.
3) For the Scanner input = new Scanner(System.in); part I get error in my eclipse, says scanner cannot be resolved to a type.
Also feel free to comment on anything need to be improved in the code. Basically just want a simple program to display all the C in a string and then count the string's occurrence. I want to then mess around the code on my own, change it so I can learn Java.
So this is my code so far:
public class Count {
static final int MAX_CHAR = 256; //is this part even needed?
public static void countString(String str)
{
// Create an array of size 256 i.e. ASCII_SIZE
int count[] = new int[MAX_CHAR];
int length = str.length();
// Initialize count array index
for (int i = 0; i < length; i++)
count[str.charAt(i)]++;
// Create an array of given String size
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 any matches found
if (str.charAt(i) == ch[j])
find++;
}
if (find == 1)
System.out.println("Number of Occurrence of " +
str.charAt(i) + " is:" + count[str.charAt(i)]);
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = "geeksforgeeks";
countString(str);
}
}
Try this
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
// Whatever is the input it take the first character.
char searchKey = input.nextLine().charAt(0);
countString(str, searchKey);
}
public static void countString(String str, char searchKey) {
// The count show both number and size of occurrence of searchKey
String count = "";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == searchKey)
count += str.charAt(i) + "\n";
}
System.out.println(count + "\nNumber of Occurrence of "
+ searchKey + " is " + count.length() + " in string " + str);
}
You could utilize the fact that each char can be used as an index into an array and use an array to count up each character.
public class Count {
static final int MAX_CHAR = 256;
private static void countString(String str, Character character) {
int [] counts = new int[MAX_CHAR];
char [] chars = str.toCharArray();
for (char ch : chars) {
if (character!=null && character!=ch) {
continue;
}
counts[ch]++;
}
for (int i=0; i<counts.length; i++) {
if (counts[i]>0) {
System.out.println("Character " + (char)i + " appeared " + counts[i] + " times");
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
countString(str, 'e');
}
}
you can take input from user "which character he/she wants to count".
To show the occurrence of character see code below.
You need to import java.util.Scanner class.
Here is your code:
import java.util.Arrays;
import java.util.Scanner;
public class Count {
public static void countString(String str)
{
if(str!=null) {
int length = str.length();
// Create an array of given String size
char ch[] = str.toCharArray();
Arrays.sort(ch);
if(length>0) {
char x = ch[0];
int count = 1;
for(int i=1;i<length; i++) {
if(ch[i] == x) {
count++;
} else {
System.out.println("Number of Occurrence of '" +
ch[i-1] + "' is: " + count);
x= ch[i];
count = 1;
}
}
System.out.println("Number of Occurrence of '" +
ch[length-1] + "' is: " + count);
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();//"geeksforgeeks";
countString(str);
}
}
See the snippet below for a way to do it in Java8
public static void main(String[] args) {
// printing all frequencies
getCharacterFrequency("test")
.forEach((key,value) -> System.out.println("Key : " + key + ", value: " + value));
// printing frequency for a specific character
Map<Character, Long> frequencies = getCharacterFrequency("test");
Character character = 't';
System.out.println("Frequency for t: " +
(frequencies.containsKey(character) ? frequencies.get(character): 0));
}
public static final Map<Character, Long> getCharacterFrequency(String string){
if(string == null){
throw new RuntimeException("Null string");
}
return string
.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
}
You just have to modify this line of code:
using for loop, print str.charAt(i) for count[str.charAt(i) times in your if statement.
if (find == 1) {
for(int k=0;k< count[str.charAt(i)];k++)
System.out.print(str.charAt(i)+",");
System.out.println(count[str.charAt(i)]);
}
Edit: modified based on your comment, if you want the whole code
import java.util.*;
public class Count {
static final int MAX_CHAR = 256; //is this part even needed?
public static void countString(String str)
{
// Create an array of size 256 i.e. ASCII_SIZE
int count[] = new int[MAX_CHAR];
int length = str.length();
// Initialize count array index
for (int i = 0; i < length; i++)
count[str.charAt(i)]++;
// Create an array of given String size
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 any matches found
if (str.charAt(i) == ch[j]){
//System.out.println(str.charAt(i));
find++;
}
}
if (find == 1) {
for(int k=0;k< count[str.charAt(i)];k++)
System.out.print(str.charAt(i)+",");
System.out.println(count[str.charAt(i)]);
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = "geeksfeorgeeks";
str = input.nextLine();
countString(str);
}
}
output
g,g,2
e,e,e,e,e,5
k,k,2
s,s,2
f,1
o,1
r,1
I know you are beginner but if you want to try new version java 8 features which makes our coding life simple and easier you can try this
public class Count {
static final int MAX_CHAR = 256;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = "geeksforgeeks";
countString(str, 'e');
}
public static void countString(String str, char value)
{
List<String> l = Arrays.asList(str.split(""));
// prints count of each character occurence in string
l.stream().forEach(character->System.out.println("Number of Occurrence of " +
character + " is:" + Collections.frequency(l, character)));
if(!(Character.toString(value).isEmpty())) {
// prints count of specified character in string
System.out.println("Number of Occurrence of " +
value + " is:" + Collections.frequency(l, Character.toString(value)));
}
}
And this is the code with requirements mentioned in comments
public class Count {
static final int MAX_CHAR = 256;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = "geeksforgeeks";
countString(str, 'e');
}
public static void countString(String str, char value)
{
String[] arr = str.split("");
StringBuffer tempString = new StringBuffer();
for(String s:arr) {
tempString.append(s);
for(char ch:s.toCharArray()) {
System.out.println("Number of Occurrence of " +
ch + " is:" + tempString.chars().filter(i->i==ch).count());
}
}
if(!(Character.toString(value).isEmpty())) {
StringBuffer tempString2 = new StringBuffer();
for(String s:arr) {
tempString2.append(s);
for(char ch:s.toCharArray()) {
if(ch==value) {
System.out.println("Number of Occurrence of " +
ch + " is:" + tempString2.chars().filter(i->i==ch).count());
}
}
}
}
}
}
You can use this code below;
import java.util.Scanner;
public class Count {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
char key = input.nextLine().charAt(0);
countString(str, key);
}
public static void countString(String str, char searchKey) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == searchKey)
count++;
}
System.out.println("Number of Occurrence of "
+ searchKey + " is " + count + " in string " + str);
for (int i = 0; i < count; i++) {
System.out.println(searchKey);
}
if (count > 0) {
System.out.println(count);
}
}
}
I would create a method such as the one below:
public static String stringCounter(String k) {
char[] strings = k.toCharArray();
int numStrings = strings.length;
Map<String, Integer> m = new HashMap<String, Integer>();
int counter = 0;
for(int x = 0; x < numStrings; x++) {
for(int y = 0; y < numStrings; y++) {
if(strings[x] == strings[y]) {
counter++;
}
}m.put(String.valueOf(strings[x]), counter);
counter = 0;
}
for(int x = 0; x < strings.length; x++) {
System.out.println(m.get(String.valueOf(strings[x])) + String.valueOf(strings[x]));
}
return m.toString();
}
}
Obviously as you did, I would pass a String as the argument to the stringCounter method. I would convert the String to a charArray in this scenario and I would also create a map in order to store a String as the key, and store an Integer for the number of times that individual string occurs in the character Array. The variable counter will count how many times that individual String occurs. We can then create a nested for loop. The outer loop will loop through each character in the array and the inner loop will compare it to each character in the array. If there is a match, the counter will increment. When the nested loop is finished, we can add the character to the Map along with the number of times it occurred in the loop. We can then print the results in another for loop my iterating through the map and the char array. We can print the number of times the character occurred as you mentioned doing, along with the value. We can also return the String value of the map which looks cleaner too. But you can simply make this method void if you don't want to return the map. The output should be as follows:
I tested the method in the main method by entering the String "Hello world":
System.out.println(stringCounter("Hello World"));
And here is our final output:
1H
1e
3l
3l
2o
1
1W
2o
1r
3l
1d
{ =1, r=1, d=1, e=1, W=1, H=1, l=3, o=2}
You get the number of times each character occurs in the String and you can use either the Map or print the output.
Now for your scanner. To add the Scanner to the program here is the code that you will need to add at the top of your code to prompt the user for String input:
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a String: ");
String str = scan.nextLine();
System.out.println(stringCounter(str));
You have to create the Scanner Object first, adding System.in to the constructor to get input from the keyboard. You can then prompt the user with a print statement to enter a String. You can then create a String variable which will store the String by calling the "Scanner.nextLine()" method as the value. This will grab the next line of userinput from the keyboard. Now you can pass the userinput to our method and it will operate the same way. Here is what it should look like to the user:
Please enter a String:
Hello World
1H
1e
3l
3l
2o
1
1W
2o
1r
3l
1d
{ =1, r=1, d=1, e=1, W=1, H=1, l=3, o=2}

Exercise about reading sentences in Java

I'm trying to read a sentence in Java and to know how many words are in there. This is what I've done:
public class TestWords {
public static void main(String[] args) {
System.out.println("Give your phrase");
Scanner extr=new Scanner(System.in);
String Phrase;
Phrase = extr.nextLine();
int TotalSizeOfPhrase = Phrase.length();
double number;
for (int i=0; i < TotalSizeOfPhrase; i++)
{
if (Phrase[i] != number && Character.isWhitespace(s.charAt(i)))
{
TotalWords = TotalWords + 1;
}
}
}
}
And I'd like to know how to code this:
if (Phrase[i]!= 'of an **arbitrary** number && white space')
then:
TotalWords = TotalWords + 1;
Because it marks a mistake when I type this:
Character.isWhitespace(s.charAt(i))
There are couple of mistakes
System.out.println("Give your phrase : ");
Scanner scan = new Scanner(System.in);
String Phrase;
Phrase = scan.nextLine();
System.out.println("Enter age : ");
int number = scan.nextInt();
// replace the number with empty string mean nothing
Phrase = Phrase.replace(String.valueOf(number), "");
Phrase = Phrase.concat(" "); // add space at end for loop calculation
int TotalSizeOfPhrase = 0; // set tot =0
int count=0; // a count variable to keep track of the word length
for (int i=0; i<Phrase.length(); i++)
{
count++;
if(Character.isWhitespace(Phrase.charAt(i)))
{
if(count-1>1){ // if size of word ( -1 is there for space size)
// is greater than 1 than increment count
TotalSizeOfPhrase=TotalSizeOfPhrase+1;
}
count=0;
}
}
System.out.println(TotalSizeOfPhrase);
scan.close();// don't forget
Inuput :
Hello i'm 20 and I'm a beginner
20
output :
5
The way i would do it, is to split the line by white spaces (getting the words), adding them to array and then getting this array length which would be equal to word count.
Phrase = Phrase.trim(); //make sure there is no spaces at start or end of the line
String[] words = Phrase.split(" "); //get the words
int word_count = words.length; //get the word count in line
if you want to get the number of words in the sentence , you could use this code :
int numberOfWords = Phrase.trim().isEmpty() ? 0 : trim.split("\\s+").length;
You can use this code:
public static void main(String[] args) {
System.out.println("Give your phrase");
Scanner extr = new Scanner(System.in);
String Phrase;
Phrase = extr.nextLine();
String[] words = Phrase.trim().split(" ");
System.out.println("Totals Number Of Words: " + words.length);
for (String word : words) {
System.out.println(word.trim());
}
}

This is only returning the largest letter word, when I want it to return the count for every letter word

I need to get this code to take the user input and tell me how many one-letter words, two-letter words, three-letter words, etc. there are. This code compiles, but it only gives me the number of times the word with the most letters is used. For example, if the user input were "I want to know why this is not working" The output would be one seven-letter word. It doesn't tell me how many times all the other number of letter words are used.
import java.util.*;
import java.io.*;
public class Analysis B { //open class
public static String input;
public static String stringB;
public static void main (String args []) { //open main
System.out.println("Please enter a line of text for analysis:");
Scanner sc = new Scanner(System.in);
input = sc.nextLine();
input = input.toLowerCase();
System.out.println("Analysis B:");//Analysis B
System.out.println("Word length: " + " Frequency: ");
System.out.println(AnalysisB(stringB));
} // close main
public static String AnalysisB (String stringB) { // open analysis B
String [] words = input.split(" ");
int largest = 0;
for (int i = 0; i < words.length; i++) { //open for
largest = Math.max( words[i].length(), largest); // get the largest value
} //close for
int [] frequencies = new int[ largest + 1 ];
for (int i = 0; i < words.length; i++) { //open for
frequencies[words[i].length()]++;
} //close for
for (int i = 0; i < frequencies.length; i++) { //open for
if (frequencies[i] > 0 ) { //open if
stringB =(i + "-letter words" + " " + frequencies[i]);
} //close if
} //close for
return stringB;
} // close analysis B
} //close class
Here's your problem:
stringB =(i + "-letter words" + " " + frequencies[i]);
Each time this line of code is run, it assigns a new value to stringB, over-writing the previous value. Instead, you want it to look like this:
stringB += (i + "-letter words" + " " + frequencies[i] + "\n");
The += operator will add to stringB instead of replacing it (and the "\n" will ensure it adds to a new line each time).
By the way, there's no need to import java.io.*, since it isn't used in your program. java.io deals with file operations.
Here's a way to do this with a sorted HashMap (TreeMap):
public static void AnalysisB (String input)
{
String [] words = input.split(" ");
Map<Integer, Integer> map = new TreeMap<Integer, Integer>();
for (String w : words)
{
int len = w.length();
Integer freq = map.get(len);
if (freq == null)
{
map.put(len, 1);
}
else
{
map.put(len, freq + 1);
}
}
for (Iterator<Integer> iter = map.keySet().iterator(); iter.hasNext(); )
{
int len = iter.next();
System.out.println(len + "-letter words" + " " + map.get(len));
}
}
Note: I made the method void since you are just printing out the frequencies in the method.
Try this.
public static String AnalysisB (String stringB) {
return Stream.of(stringB.split(" "))
.map(s -> s.length())
.collect(Collectors.groupingBy(n -> n, Collectors.counting()))
.entrySet().stream()
.sorted(Comparator.comparing(e -> e.getKey()))
.map(e -> e.getKey() + "-letter words " + e.getValue())
.collect(Collectors.joining("\n"));
}
and
System.out.println(AnalysisB("I want to know why this is not working"));
result:
1-letter words 1
2-letter words 2
3-letter words 2
4-letter words 3
7-letter words 1

Splitting an array to be input into a Map

I am trying to split an array of names such as "Joe Bloggs" Joe and Bloggs are separate and then can be used in a map where the first name is the key. Here is what I have so far.
public static void main(String[] args) {
Map<String, String> snames = new HashMap<String, String>();
int index = -1;
String[] names = new String[8];
Scanner s = new Scanner( System.in );
for( int i = 0; i <= names.length; i++ ){
System.out.println( "Enter student name:" );
names[ i ] = s.next();
}
System.out.println("Please type in the student index you want to view between 0 and 7");
index = s.nextInt();
while (index >7 || index <0){
System.out.println("Please type in a valid index value");
index = s.nextInt();
}
System.out.println("The student with the index of " + index + " is " + names[index]);
}
}
Not too sure what you are asking for
for (String x : names){
String[] temp = x.split(" "); // split "Joe Bloggs" to ["Joe", "Bloggs"]
if (temp.length == 2){
snames.put(temp[0], temp[1]); // Mapping "Joe" to "Bloggs"
}
}
is that what you want?

Categories

Resources