Splitting an input that doesn't have blank spaces - java

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

Related

ArrayIndexOutOfBoundsException when finding words in an array that and with a specific letter

I am trying to find words in an array that end with a letter 'a'. I thought of doing it using two for loops but I keep getting integer out of bounds error.
Could anyone tell me what i am doing wrong?
The code:
Scanner sc = new Scanner(System.in);
System.out.println("Enter text: ");
String text = sc.nextLine();
String[] words = text.split(" ");
for (int i = 0; i < words.length; i++) {
words[i] = words[i] + " ";
}
for (int i = 0; i < words.length ; i++) {
for (int j = 0; j <= words[i].charAt(j); j++) {
if (words[i].charAt(j) == 'a' && words[i].charAt(j + 1) == ' ') {
System.out.println(words[i]);
}
}
}
You've got too much code for the task, which has lead to a bug creeping in and hiding in plain sight. As a general rule, keeping code as simple as possible results in less bugs.
Delete this, which you don't need.
for (int i = 0; i < words.length; i++) {
words[i] = words[i] + " ";
}
And delete all of this:
for (int j = 0; j <= words[i].charAt(j); j++) {
if( words[i].charAt(j) == 'a' && words[i].charAt(j + 1) == ' '){
System.out.println(words[i]);
}
}
instead basing your code on endsWith("a"):
for (String word : words) {
if (word.endsWith("a")) {
System.out.println(word);
}
}
which is easy to read and understand (and thus easier to avoid bugs).
Even simpler, since you don't need to reference the array, use the result of the split directly:
String text = sc.nextLine();
for (String word : text.split(" ")) {
if (word.endsWith("a")) {
System.out.println(word);
}
}
In your second for loop, you are checking against the character at the current position, not the length of the word. Change the condition to words[i].length()to fix it.
In order to check if some words end with character a, we can do the following:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Read the input
System.out.println("Enter text: ");
String text = sc.nextLine();
// Split the input by spaces
String[] words = text.split(" ");
// Iterate through the array of words and check if any of those ends with "a"
for (String word : words) {
if (word.endsWith("a")) {
System.out.println(word);
}
}
}
It would be simple as that, we don't really need an embedded loop.
Try this instead
String[] words = {"apple", "ada", "cat", "material", "recursion", "stacksa"};
for (int i = 0; i < words.length; i++) {
// get each word first
String word = words[I];
int lenOfWord = word.length();
// check the last item in the word
if (word.charAt(lenOfWord - 1) == 'a') {
System.out.println("Last char is a" + word);
}
}
Other answers explain the logic via loops. Another approach to do the same could be through Java streams:
Scanner sc = new Scanner(System.in);
System.out.println("Enter text: ");
String text = sc.nextLine();
String[] words = text.split(" ");
Arrays.stream(words).filter(w -> w.endsWith("a")).forEach(System.out::println);

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

to print all the words in a string which starts and ends with same letter in java

*
import java.util.*;
class Word{
void main(){
char ch='\u0000',firstc,lastc;
int c=0,lw; String w="",s1="";
Scanner in = new Scanner(System.in);
System.out.println("Enter a String");
String n = in.nextLine();n=n+"";
for (int i=0;i<n.length();i++){
ch = n.charAt(i);
if(ch!=' '){
w=w+ch;
}else{
firstc = w.charAt(0);
lastc = w.charAt(w.length()-1);
if(firstc==(lastc))
s1=s1+w;
System.out.println(""+s1);
}
}
w=" ";
}
}
*
Now the output comes for one string like if I give MADAM HAVE A MODEM as input it only gives me MADAM as output.
You have to split your "in" string by spaces " ".
After that, if both characters at the start and at the end.
Notice String.charAt() method will get characters from position 0 (start) to the string lenght - 1.
Scanner in = new Scanner(System.in);
System.out.println("Enter a String");
String n = in.nextLine();
String[] parts = n.split(" ");
for(String part : parts) {
if(part.charAt(0)==part.charAt(part.length()-1)) {
System.out.println(part);
}
}
Your code is overly complicated. It would be much simpler to either split the string on space or just read one word at a time:
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
// Get next word
String s = in.next();
if (Character.toLowerCase(s.charAt(0)) == Character.toLowerCase(s.charAt(s.length() - 1))) {
System.out.println(s);
}
}
But back to your code, I see these issues.
It will always skip the last word
You reset w outside of the for and it should be w = "";
Your indentation is really bad
Your code fixed (well, at least working):
char firstc, lastc;
String w = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a String");
String n = in.nextLine();
for (int i = 0; i < n.length(); i++) {
ch = n.charAt(i);
if (ch != ' '){
w = w + ch;
}
if (ch == ' ' || i == n.length()-1) {
firstc = w.charAt(0);
lastc = w.charAt(w.length()-1);
if (firstc == lastc) {
System.out.println(w);
}
w="";
}
}

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

java program to count the number of words that starts with capital letters

I want to write a program that count the number of words that starts with capital letters. It only count no. Of capital letter not word try this line
"Hi hOw are yOu"
According to my code output will be 3
But their is only 1 word that starts with capital letter that is 'Hi'...so how can I solve these problem..Please help me with this.
import java.util.*;
class Cap
{
public static void main(String m[])
{
Scanner in=new Scanner(System.in);
String s=new String();
System.out.println("Enter a line:");
s=in.nextLine();
char c;
int ct=0;
for(int i=0;i<s.length();i++)
{
c=s.charAt(i);
if(c>=65 && c<=90)
{
ct++;
}
}
System.out.println("total number of words start with capital letters are :"+ct);
}
}
You should better use scanner.next();, which returns the token up to white space in other way a word.Now, you can check the first character of String returned by next() is in uppercase or not.
For statement This is StackOverflow you will have three tokens, This, is and StackOverflow and you can use String.charAt(0) on this String.
Moreover, you can simply use Character.isUpperCase method to check whether character is in upper case or not.
import java.util.*;
public class program_6
{
public static void main(String[] args)
{
String s1;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string... ");
s1 = scan.nextLine();
int count=0,i=0,n;
n = s1.length();
System.out.println("Size of the string is... " + n );
if ( null == s1 || s1.isEmpty())
{
System.out.println("Text empty");
}
else
{
if( Character.isUpperCase(s1.charAt(0) ))
{
count++;
}
for (i=1 ; i<n ; i++)
{
if ( Character.isWhitespace(s1.charAt(i-1)) && Character.isUpperCase(s1.charAt(i) ) )
{
count++;
}
}
}
System.out.println("Number of the word wich starts with capital latter... " + count );
}
}
Currently you are counting all the capital letters that are entered.
What you want to do is split the line on space and check only for the first letter if it is capital.
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String s;
System.out.println("Enter a line:");
s=in.nextLine();
int ct=0;
for(String str: s.split(" ")) {
if(str.charAt(0)>=65 && str.charAt(0)<=90)
{
ct++;
}
}
System.out.println("total number of words start with capital letters are :"+ct);
}
You are comparing each character.Instead you can add a space at the begining of the string and check each character after space if it is in uppercase.
Scanner in = new Scanner(System. in );
String s = new String();
System.out.println("Enter a line:");
s = " " + in .nextLine().trim();
char c;
int ct = 0;
for (int i = 1; i < s.length(); i++) {
c = s.charAt(i);
if (c >= 65 && c <= 90 && s.charAt(i - 1) == 32) {
ct++;
}
}
System.out.println("total number of words start with capital letters are :" + ct);
DEMO
or better use scanner.next() as said by TAsk
Try this:
Scanner in = new Scanner(System.in);
String s = new String();
System.out.println("Enter a line:");
s = in.nextLine();
char c;
int ct = 0;
for (int i = 0; i < s.length(); i++) {
c = s.charAt(i);
if (Character.isUpperCase(c)
&& (i == 0 || Character.isWhitespace(s.charAt(i - 1)))) {
ct++;
}
}
System.out
.println("total number of words start with capital letters are :"
+ ct);
First of all we check on the first position whether it is starts with capital letter or not and it is only for the string which starts with capital letter... If yes then the count will be incremented. Next condition( Which is used for string which start with blank space or any other string) will check that left position must have blank space to start new word and the character must be capital to increment the count variable...
import java.util.*;
public class program_6
{
public static void main(String[] args)
{
String s1;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string... ");
s1 = scan.nextLine();
int count=0,i=0,n;
n = s1.length();
System.out.println("Size of the string is... " + n );
if ( null == s1 || s1.isEmpty())
{
System.out.println("Text empty");
}
else
{
if( Character.isUpperCase(s1.charAt(0) ))
{
count++;
}
for (i=1 ; i<n ; i++)
{
if ( Character.isWhitespace(s1.charAt(i-1)) && Character.isUpperCase(s1.charAt(i) ) )
{
count++;
}
}
}
System.out.println("Number of the word wich starts with capital letter... " + count );
}
}

Categories

Resources