'WAP to accept a string and print only the words having consecutive letters as same and number of occurrences [duplicate]
I was solving this question(the title) and I cant find the mistakes present so please help
Input : The buffalo is stuck in a soggy field and roads are flooded everywhere.
Output : buffalo, soggy, flooded
There are 3 words that have consecutive letters.
package com.company;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence");
String str = sc.nextLine();
str = str.toUpperCase();
String s = " ";
int count = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch != ' ')
s = s + ch;
else {
for (int j = 0; j < s.length(); j++) {
if (s.charAt(j) == s.charAt(j + 1)) {
System.out.println(s);
count++;
s = " ";
}
}
}
}
System.out.println("There are " + count + " consecutive words");
}
}
Output
Enter the sentence
I love apples
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
at java.base/java.lang.String.charAt(String.java:1512)
at com.company.Main.main(Main.java:18)
Process finished with exit code 1
I tried solving it but it gets complicated as such
Solution 1:[1]
Here:
for (int j = 0; j < s.length(); j++){
if (s.charAt(j) == s.charAt(j + 1)){
System.out.println(s);
count++;
s = " ";
}
}
You are looping through a string comparing the j index character with the j+1 index character. When j is the index of the last character j+1 will be out of range. If you want to do the comparation this way, you just have to go to the penultimate index (where you will compare the penultimate with the last).
This way the code should work:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence");
String str = sc.nextLine();
str = str.toUpperCase();
String s = " ";
int count = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch != ' ')
s = s + ch;
else {
for (int j = 0; j < s.length()-1; j++) {
if (s.charAt(j) == s.charAt(j + 1)) {
System.out.println(s);
count++;
}
}
s = " ";
}
}
System.out.println("There are " + count + " consecutive words");
}
And as you can see I have moved the s = " "; piece of code outside of the for and if block, leaving it just inside the else block. If you don't do that the string variable s will not be cleaned after each word.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Calico Jack |