Program counts dots(.) as alphabetic characters - java

So my task was to create a program that takes a file as input and counts the occurrences of each alphabetic character in it. Then I shall print the letter, the amount of times it occurs and the frequency of it.
And I get it to work almost as planned. The only problem I have is that when I print, it also prints the number of dots(.) in the file. And I can't stop it from doing that. Help please..
public class CountOccurences {
private static Scanner input;
public static void main(String [] args) throws FileNotFoundException {
DecimalFormat dec = new DecimalFormat("#.000");
input = new Scanner(new File("story.txt"));
int[] ltrCtr = new int[127]; // This array counts the number of occurences for every letter / symbol on the ascii table.
String str = "";
// Puts the textfile as a String
while(input.hasNext()) {
str += input.next();
}
char[] text = str.toCharArray();
char temp; int tempInt;
int ctr = 0;
for(int i = 0; i < text.length; i++) { // Loops through the text
temp = text[i]; // Gets the char at i
tempInt = (int)temp; // Get the ascii value of the char at i
ltrCtr[tempInt]++;
if(Character.isAlphabetic(text[i])) {
ctr++;
}
}
System.out.println("Letter" + " Amount" + " Freq");
for(int i = 0; i < ltrCtr.length; i++) {
if(ltrCtr[i] >= 1 && (int)ltrCtr[i] != 46) {
System.out.println(" " + (char)i + " " +
ltrCtr[i] + " " +
dec.format((double)ltrCtr[i]/ctr) + "%");
}
}
input.close();
}
}

I believe you meant to use isLetter, not isAlphabetic.

Mureinik is right, isLetter solves your problem. Here's a post explaining the differences between isLetter and isAlphabetic to make it clearer: What is the difference between Character.isAlphabetic and Character.isLetter in Java?

Related

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}

Counting upper-case characters in array with strings

So i'm trying to count the number of upper-case characters in a array with strings. I'm at a brick wall here. If someone could shed some light on my problem that would be fantastic.
I assume the same loop can be done with just Character.isLowerCase(item) as well right?
After this is completed I also have to tell the user the longest string in the array and how many characters the longest string has as well which I really don't know how to do.
Professor really threw a curve ball at us with this one..
So here's my code so far:
// Program3.java
// Brandin Yoder
// 2/23/18
// Store strings in an array and tell user number of upper-case and lower-case characters,
// and spaces
import java.util.Scanner;
public class Program3
{
public static void main(String[] args)
{
// Set up keyboard.
Scanner keyboard = new Scanner(System.in);
// Input number of strings to store.
System.out.print("Number of strings to input: ");
int nrStrings = keyboard.nextInt();
// Clear keyboard buffer.
keyboard.nextLine();
// Set up array to hold strings.
String[] strings = new String[nrStrings];
// Input strings from keyboard.
System.out.println("\nInput strings:");
for(int ctr = 0; ctr < nrStrings; ctr++)
{
System.out.print("String #" + (ctr+1) + " :");
strings[ctr] = keyboard.next();
}
// Print back strings input.
System.out.println("\nStrings input:");
for(int ctr = 0; ctr < nrStrings; ctr++)
{
System.out.println("String #" + (ctr+1) + ": " + strings[ctr]);
}
// Set up variables for upper-case, lower-case and white space calculator.
int UpperNr = 0;
int LowerNr = 0;
int Spaces = 0;
// For loop that determines amount of Upper-Case numbers.
for(int ctr = 0; ctr < nrStrings; ctr++)
{
char item = strings[ctr].charAt(ctr);
if(Character.isUpperCase(item))
UpperNr++;
}
System.out.println(UpperNr);
}
}
You need to create variables to hold the data that you want to print out at the end. In this case you need to maintain an array that has the number of Uppercases for each string as well as the index and length of the longest string. You have to use a nested for loop to iterate through the array of strings that you have and also the strings themselves in order to check how many Uppercase characters you have. I have modified/commented the last part of your code below.
//array that contains number of uppercase letters in each string
int[] upperAmount = new int[nrStrings];
//index of the longest string
int maxLenIndex = 0;
//length of longest string
int maxLength = 0;
//array that iterates through all the strings in the array strings[]
for(int i = 0; i<strings.length;i++){
//if the new string is the longest
if(strings[i].length() > maxLength){
//set maxlength to the new length and record index of string
maxLength = strings[i].length();
maxLenIndex = i;
}
// For loop that determines amount of Upper-Case numbers.
for(int ctr = 0; ctr < strings[i].length(); ctr++)
{
char item = strings[i].charAt(ctr);
if(Character.isUpperCase(item))
UpperNr++;
}
//add number of uppercases to upperAmount array indexes will be the same
upperAmount[i] = UpperNr;
//reset upper number
UpperNr = 0;
}
// Print back strings input.
System.out.println("\nStrings input:");
for(int ctr = 0; ctr < nrStrings; ctr++)
{
System.out.println("String #" + (ctr+1) + ": " + strings[ctr]);
System.out.println("Number of Uppercase Letters: " + upperAmount[ctr]);
}
System.out.println("MaxStringLength: " + maxLength);
System.out.println("Max String: " + strings[maxLenIndex]);
}
I hope this solves your problem
//after you finish printing the strings
String strMax="";
int ctr=0;
for(String str :strings ){
strMax = str.length()>strMax.length()?str:strMax;
if(!str.equals(str.toLowerCase())){
for(char c : str.toCharArray()){
if(Character.isUpperCase(c))
ctr++;
}
}
}
System.out.println("Longeset String"+strMax );
System.out.println("total Upper case chars" +ctr);
Is it neccesarry to input the count of strings? I think you can accept one whole string and convert it into array of chars
char[] charArray = acceptedString.toCharArray;
Then go throw all chars, and where charArray[n] > 64 && charArray[n] < 91 increase your variable to counting UpperCases. Hope you understand) Ask if you have questions.
Scanner keyboard = new Scanner(System.in);
String inString = keyboard.nextLine();
char[] symbol = inString.toCharArray();
int count =0;
for(int i =0; i < symbol.length; i++){
if(symbol[i] > 64 && symbol[i] < 91){ //cause every char has its own number in Unicode. 'A' = 65 and 'Z' = 90
count++;
}
}
System.out.print(count);

What variable needs to be identified?

I am a beginner in java. There is an error which appears 15 times in lines 24, 27, 29, 30, 35, 36, 37, 42, 43 and 46, saying:
//Tokens cannot be resolved to a variable
And:
// i cannot be resolved to a variable
What variables do these errors want to identify? Because I thought I identified everything and I don't understand what variables my code still needs.
Here is my code:
import java.util.Scanner;
public class Jo_code {
public static int wordFrequency(String s) {
String tokens[] = s.split(" ");// splits the words
int count = tokens.length;
return count;
}
public static void main(String args[]) {
System.out.println("Write your sentence or type END to quit the program:");// prints out the first instruction.
Scanner scan = new Scanner(System.in); //object initialisation.
String line = " ";//declaration for letters(String) characters.
int max = 20; //declaration for number(int) characters.
while ((line = scan.nextLine()) != null) { //scanner instruction, get a line from the key board.
if (line.equals("END")) {
break;// if you are happy with the code, then type "END", and the code will stop running.
} else { // if you decide not to type "END" the program will continue to allow you to type sentences.
String[] array = line.split(" ");// splits the words
System.out.println("your sentence is " + line);//prints out what you have typed.
System.out.println("The total of words for the line is " + tokens.length);// prints out the total of words that you have typed.
int maxTokensLength = 0;
int tokensLength = 0;
for (int i = 0; i < tokens.length; i++) {// this line of code checks for what must be true to carry on.
array[i] = array[i].replaceAll("a-zA-Z]", "");
}
tokensLength = array[i].length();
tokensLength = tokens[i].length();
if (tokensLength > maxTokensLength) {
maxTokensLength = tokensLength;
}
}
}
int[] intArray = new int[maxTokensLength + 1];
for (int i = 0; i < tokens.length; i++) { // this line of code checks for what must be true to carry on.
intArray[array[i].length()]++;
}
for (int i = 1; i < intArray.length; i++) { // this line of code checks for what must be true to carry on.
System.out.printf("%word(s) of length %d<br>", intArray[i], i);
}
for (int i = 0; i < tokens.length; i++) { // this line of code checks for what must be true to carry on.
System.out.println("word " + i + ": " + tokens[i] + " = " + tokens[i].length() + " characters");
}
System.out.println("The length for the word " + tokens[i] + " is = " + tokens[i].length());//This line of code prints out the word frequency for each word.
System.out.println("The word frequency of the whole sentence is =");//results
System.out.println("type END to quit");//instructions
}
}
Thank you very much for any help, its much appreciated!
For one thing, your very first for loop has no open and close brackets. This means only the first statement is considered part of the for loop. so the statement 'tokensLength = array[i].length();' can't reach the variable i because it is not in the for loop. I believe adding open and close brackets around everything you want in the first for loop should fix it

Java : Occurances of a character in a String

I need help on my code in Java.
This is the problem :
Example input : AaaaaAa
Output : A appears 7.
The problem is I need it to ignore cases.
Please help me, my code works fine, except that it doesn't ignore cases.
import java.io.*;
public class letter_bmp{
public static BufferedReader input = new BufferedReader( new InputStreamReader(System.in));
public static void main(String[] args) throws Exception
{
String string1;
String pick;
String ans;
do
{
int count=0;
System.out.print("En taro Adun, Executor! Input desired string : ");
string1 = input.readLine();
System.out.print("Now, Executor...which character shall I choose : ");
pick = input.readLine();
for(int counter = 0; counter < string1.length(); counter++)
{
if(pick.charAt(0) == string1.charAt(counter))
count++;
}
System.out.print("Executor...you picked '" + pick + "' it is used " + count + " times in the word "+string1+".");
System.out.println("\nWould you like to try again, Executor? (Yes/No): ");
ans = input.readLine();
}
while(ans.equalsIgnoreCase("Yes"));
}
}
Convert the string to lower case characters using the String.toLowerCase() method.
// ...
string1 = input.readLine().toLowerCase();
// ...
pick = input.readLine().toLowerCase();
// ...
The easiest solution is to make 2 new strings like this:
string1_lower = string1.toLowerCase();
pick_lower = pick.toLowerCase();
And use those two variables during comparison.
I understand that the question is old and the OP might have got his answer. But i am putting this out here just in case if anybody needs it in the future.
public static void main(String[] args) {
String s="rEmember";
for(int i = 0; i <= s.length() - 1; i++){
int count = 0;
for(int j = 0; j <= s.length() - 1; j++){
if(Character.toLowerCase(s.charAt(i)) == Character.toLowerCase(s.charAt(j))){
count++;
}
}
System.out.println(s.charAt(i) + " = " + count + " times");
}
}

out of bounds error with word count

I'm trying to write my own Java word count program. I know there may already be a method for this, but I'd like to get it work. I'm getting an out of bounds error at line 14. I'm trying to use an input word to count how many times it appears in an input string. So I'm looping up to stringlength - wordlength, but that's where the problem is.
Here is the code:
import java.util.Scanner;
public class wordcount {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print( "Enter word : " );
String word = s.nextLine();
Scanner t = new Scanner(System.in);
System.out.print("Enter string: ");
String string = t.nextLine();
int count = 0;
for (int i = 0; i < string.length()-word.length(); i = i+1){
String substring = string.substring(i,i+word.length());
if (match(substring, word)==true){
count += 1;
}
}
System.out.println("There are "+count+ " repetitions of the word "+word);
}
public static boolean match(String string1, String string2){
for (int i=0; i<string1.length(); i+=1){
if (string1.charAt(i)!=string2.charAt(i)){
return false;
}
}
return true;
}
}
First of all, two Scanners are not necessary, you can do many inputs with the same Scanner object.
Also, this if condition
if (match(substring, word) == true)
can be rewritten like
if (math(substring, word))
I would also recommend you to use i++ to increase the loop variable. Is not strictly necessary but is "almost" a convention. You can read more about that here.
Now, about theIndexOutOfBoundsException, I've tested the code and I don't find any input samples to get it.
Besides, there is an issue, you are missing one iteration in the for:
for (int i = 0; i < string.length() - word.length() + 1; i++) { // Add '+ 1'
String substring = string.substring(i, i + word.length());
// System.out.println(substring);
if (match(substring, word)) {
count++;
}
}
You can test it by putting a print statement inside the loop, to print each substring.
I'm not getting an out of bounds error, can you tell me what values you were using for word and string?
I have identified a bug with your program. If word is equal to string, it still returns count 0. I suggest adding one more iteration and using regionMatches instead. RegionMatches makes your match method obsolete and will return false if word.length() + i is equal or greater than string.length(), avoiding out of bounds issues.
As you can see I also moved the calculations to a seperate method, this will make your code more readable and testable.
And as Christian pointed out; you indeed do only need one Scanner object. I've adapted the code below to reflect it.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter word : ");
String word = sc.nextLine();
System.out.print("Enter string: ");
String string = sc.nextLine();
int count = calculateWordCount(word, string);
System.out.println("There are " + count + " repetitions of the word " + word);
}
private static int calculateWordCount(String word, String string) {
int count = 0;
for (int i = 0; i < string.length() - word.length() + 1; i++) {
if (word.regionMatches(0, string, i, word.length())) {
count++;
}
}
return count;
}

Categories

Resources