Here is my homework:
accept a sentence and print the words that have consecutive characters equal
INPUT: an apple a day keeps
OUTPUT: apple keeps
Here is what I am working on:
import java.util.*;
public class Program1
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a sentence");
String s=sc.nextLine();
String str=s.toLowerCase();
int l,i=0; char c,d;int a,b,m=0;int n=0; String r=""; String res="";
l=s.length();
str=" "+str+" ";
for(i=0;i<(l-1);i++)
{
c=str.charAt(i);
d=str.charAt(i+1);
a=c;
b=d;
m=str.indexOf(' ');
n=str.indexOf(' ',(i+1));
if(d==' ')
{
m=str.indexOf(' ',(i-1));
n=str.indexOf(' ',(i+1));
}
if(a==b)
{
r=str.substring(m,n);
res=res +" "+ r;
}
}
System.out.println(res);
}
}
It gets compiled, but it does not give correct output.
If I enter the above example, it returns:
an apple an apple a day keeps
What do I need to do?
You can do something like this to achieve the result,
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence");
String s = sc.nextLine();
String str = s.toLowerCase();
String[] words = str.split(" "); // Split the sentence into an array of words.
for(String ss : words){
char previousChar = '\u0000';
for (char c : ss.toCharArray()) {
if (previousChar == c) { // Same character has occurred
System.out.println(ss);
break;
}
previousChar = c;
}
}