Counting upper-case characters in array with strings - java

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);

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).

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

Program counts dots(.) as alphabetic characters

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?

Counting Upper and Lower characters in a string using an array

I have been working on this problem for two days now and have no idea where I'm going wrong.
Essentially I need to ask a user for a string of words.
I need to set up an int array of 26 elements that holds the count of lower case letters and one for upper case letters.
I can't get the program to compare with the array elements properly. This is my code so far:
public class Lab17Array {
public static void main(String[] args)
{
Scanner kb = new Scanner (System.in);
int lLetter = 0;
int uLetter = 0;
// int[] alph = new int [26];
int alph [] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
int Alph [] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
System.out.println("Enter a phrase");
String user = kb.nextLine();
// to print out length of word
System.out.println("Total number of letters is " + user.length());
for(int i = 0; i < user.length(); i++)
{
}
System.out.println("Upper case letters are:" + uLetter);
System.out.println("Lower case letters are:" + lLetter);
int otherL = user.length() - (uLetter + lLetter);
// to print out other chars that aren't letters
System.out.println("Number of all other letters is " + otherL );
}
}
Inside my for loop is where I've been trying different if conditions. I have no idea what I'm missing?
Using an Array
You could use String.toCharArray() and a for-each loop to iterate your userInput (you seem to have changed the variable name between your post, and your comment). Regardless, something like
for (char ch : user.toCharArray()) {
if (Character.isLowerCase(ch)) {
lLetter++;
} else if (Character.isUpperCase(ch)) {
uLetter++;
}
}
Using Regular Expression(s)
You could reduce your code by using a regular expression to remove all non-lowercase characters from the input and another to remove all non-uppercase characters from the input like
int lLetter = user.replaceAll("[^a-z]", "").length(); // <-- removes everything not a-z
int uLetter = user.replaceAll("[^A-Z]", "").length(); // <-- removes everything not A-Z
Try this
int upperCount = 0;
int lowerCount = 0;
Scanner sc = new Scanner(System.in);
String w = sc.nextLine();
for(int i = 0; i < w.length(); i++){
if(Character.isUpperCase(w.charAt(i))){
upperCount++;
}else{
lowerCount++;
}
}
System.out.println("Upper Counts are "+upperCount+" lower counts are "+lowerCount);
Try this.
for(int i = 0; i < user.length(); i++)
{
int ch = user.charAt(i);
if (Arrays.binarySearch(alph, ch) >= 0)
++lLetter;
if (Arrays.binarySearch(Alph, ch) >= 0)
++uLetter;
}

How to create a program that uses an array to count vowels?

I am having some trouble creating a program that uses an array to count vowels in names entered by a user. The user should be able to enter up to 1000 names or say "Done" to end the program. Once the user gets to 1000 names or says done, it is supposed to display the total amount of vowels in each name combined.
Here is what I have so far:
import java.util.Scanner;
import java.lang.String;
import java.lang.Math;
public class Countvowels
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
final int LOW ='A';
final int HIGH = 'Z';
int[] letterCounts = new int[HIGH-LOW+1];
String[] word = new String[1000];
char[] wordLetter;
int offset;
System.out.println("Enter a name: ");
for(int letter = 0; letter < wordLetter.length; letter++){
word[letter] = input.nextLine();
wordLetter = word.toCharArray();
}
}
}
Help is much appreciated!
Never mind all that code. You only need one line:
String[] word = new String[1000]; // given this
int vowels = Arrays.toString(word).replaceAll("(?i)[^aeiou]", "").length();
This first converts the array to a string (basically a csv), then replaces all non-vowels (fyi (?i) is the case-insensitive flag) with nothing (ie deleting them), then with only vowels left just take the length.
If you need a total for all vowels #Bohemian has an excellent answer. If you need them seperate it might be easier to do the following:
Just create 1 big string with all the user input.
Then for example when you end up with:
String userInput = 'JohnMaryLisaPeter';
for(int x = 0; x <= userInput.length() - 1; x++) {
if(userInput.charAt(x) == 97)
vowelA++;
else if(userInput.charAt(x) == 101)
vowelE++;
else if(userInput.charAt(x) == 105)
vowelI++;
else if(userInput.charAt(x) == 111)
vowelO++;
else if(userInput.charAt(x) == 117)
vowelU++;
}
System.out.println("There were " + vowelA + " A's in all your names.");
System.out.println("There were " + vowelE + " E's in all your names.");
System.out.println("There were " + vowelI + " I's in all your names.");
System.out.println("There were " + vowelO + " O's in all your names.");
System.out.println("There were " + vowelU + " U's in all your names.");
Three errors I see:
You have the array-of-characters
char[] wordLetter;
in which the vowels will go, yet you're using it as the for-loop termination. There's nothing in the array yet--there is no array at all, just a marker in memory where it will be created--so you are comparing letter against nothingness!
for(int letter = 0; letter < wordLetter.length; letter++){
It should be
for(int letter = 0; letter < [some_number_here]; letter++){
In the for-loop, you are attempting to change the entire array of words to a character array, which makes no sense. Naming the array of words word is confusing you. Try aWords or something.
wordLetter = word.toCharArray();
Fix:
wordLetter = word[letter].toCharArray();
And letter is another bad choice of variable names. Try iIndex.
I hope this helps!

Categories

Resources