Counting Upper and Lower characters in a string using an array - java

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

Related

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

Count letter in a word from scanner, java

My code is looking like this right now, it's counting the letters in the word but I would like my code to count every letter in the word so if I write banana or nine, the code will ask which letter to count, and if I choose "N", it will print 2 "N". Please help me out.
System.out.println("Ange ordet du vill leta i: ");
String str1 = sc.nextLine();
System.out.println("Ange bokstaven du vill leta efter: ");
String str2 = sc.nextLine();
int count = 0;
for(int i = 0; i < str2.length(); i++) {
if(str2.charAt(i) != ' ')
count++;
}
System.out.println("Antal bokstäver i ditt ord: " + count);
You don't need to count every letter at first. You should count after getting the letter to count. But depending on the scenario. I assume that you need to get the count of the letter in a particular string.
You can wrap counting logic inside a while() to do this over and over again.
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("enter word");
String s = scanner.next();
System.out.println("enter letter");
char a = scanner.next().charAt(0);
int count = 0;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == a){
count++;
}
}
System.out.println(count);
}
}

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

Splitting an input that doesn't have blank spaces

I have an input that looks like this ABABABAABA, i want to split the input into single characters and then count the number of occurrences letter "A" and "B". this is what i have so far
import java.util.Scanner;
Scanner str = new Scanner(System.in);
String userInput = str.nextLine();
userInput.split("");
What should I do after to count how many occurrences there are of letter "A" and "B"?
You don't actually need to split it, simply iterating over it would be enough. Then you can use a map to count the occurrences like this:
Scanner str = new Scanner(System.in);
String userInput = str.nextLine();
Map<Character, Integer> occ = new HashMap<>();
for(char ch : userInput.toCharArray()) {
if(!occ.containsKey(ch)) {
occ.put(ch, 0);
}
occ.put(ch, occ.get(ch) + 1);
}
You would loop through your string and read the character with `String.charAt(index)'. No need to split at all.).
int countA = 0;
int countB = 0;
for(int index = 0; index < userInput.length(); index++)
{
char c = userInput.charAt(index);
if(c == 'A')
{
countA++;
}
else if(c == 'B')
{
countB++;
}
else
{
// some other character detected
}
}

Categories

Resources