Click here to Skip to main content
15,885,914 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have written a code in which I am trying to print the word "bad" as it is and other words I am replacing with *. The code is as follows:
import java.util.*;
import java.io.*;
import java.lang.*;

    public class wordreplaceabhinew
    {
        
       
  
     public static void main(String[]args)
        {
            Scanner sc=new Scanner(System.in);
            String comment;
            System.out.println("Enter a comment:");
            comment=sc.nextLine();
           
 
   
    for (int i = 0; i < comment.length(); i++) {
       
if(comment.charAt(i)!=' ')
{
     
      if(comment.charAt(i)=='b')
      {
         
          if(comment.charAt(i+1)=='a')
          {
             
             if(comment.charAt(i+2)=='d')
             {
              comment=comment.substring(i,i+3);
               
             }
            
          }

          else 
          {
              System.out.print("*");

          }
   
      } 
      
System.out.print("*");
         
}
else
{
    System.out.print(" ");
    
}


        
   
}
  System.out.print(comment);
 


              
        }  
    }

For example my input is "I am bad"
O/p should be "* ** bad"
But instead I am getting "* ** *bad"
I want to understand where I am going wrong?

What I have tried:

import java.util.*;
import java.io.*;
import java.lang.*;

    public class wordreplaceabhinew
    {
        
       
  
     public static void main(String[]args)
        {
            Scanner sc=new Scanner(System.in);
            String comment;
            System.out.println("Enter a comment:");
            comment=sc.nextLine();
           
 
   
    for (int i = 0; i < comment.length(); i++) {
       
if(comment.charAt(i)!=' ')
{
     
      if(comment.charAt(i)=='b')
      {
         
          if(comment.charAt(i+1)=='a')
          {
             
             if(comment.charAt(i+2)=='d')
             {
              comment=comment.substring(i,i+3);
               
             }
            
          }

          else 
          {
              System.out.print("*");

          }
   
      } 
      
System.out.print("*");
         
}
else
{
    System.out.print(" ");
    
}


        
   
}
  System.out.print(comment);
 


              
        }  
    }
Posted
Updated 24-Feb-23 0:38am

First problem: your loop variable ranges across all valid character indices within the value. But within the loop, you try to access characters at index i+1 and i+2. If, for example, your string ends with "Jacob", you will get an exception trying to access a character past the end of the string.

Second problem: you write out either a '*' or a ' ' for everything in the string apart from "bad", and then write out the remaining "bad"s at the end. If, for example, your input was "This is very bad; your teacher forbade you from doing this.", you would output: "**** ** *** ; **** ******* **** *** **** ***** *****badbad", which is clearly wrong.

Except you wouldn't, because of the third problem: as soon as you find "bad", you throw away the rest of the string. So that input would actually produce, "**** ** **** bad".

Except that's still not quite right, because of the fourth problem: you're writing out a '*' for everything that isn't a space. So when you find your first "bad", you write out a '*', terminate the loop, and the write out "bad".

Stop and think what you're trying to do. Stop modifying the input string, and write out "bad" as part of the loop.

It's your homework assignment, so no code; but you want to implement something like this:
  • If the current character is a space, write a space;
  • Otherwise, if the current character is "b", and the index is at least three less than the length, and the next two characters are "a" and "d", write "bad";
  • Otherwise, write "*";
 
Share this answer
 
v3
Comments
Abhinav Kishore M 24-Feb-23 6:55am    
Otherwise, if the current character is "b", and the index is at least three less than the length, and the next two characters are "a" and "d", write "bad";
I am confused in this thing
Richard Deeming 24-Feb-23 6:59am    
You're currently testing whether the current character is "b" and the next two characters are "a" and "d". But you're not testing whether there are two more characters to check.

As I said, if your input string ends with "b" or "ba", then your code will throw an exception.

if (i < comment.length() - 2 && comment.charAt(i) == 'b' && comment.charAt(i + 1) == 'a' && comment.charAt(i + 2) == 'd')
{
    System.out.print("bad");
}
Abhinav Kishore M 24-Feb-23 7:25am    
Thank u Richard. But now I am facing one more issue.
O/p is now coming as:
* ** bad**I am bad
The code I have here is:
for (int i = 0; i < comment.length(); i++) {

if(comment.charAt(i)!=' ')
{


if (i < comment.length() - 2 && comment.charAt(i) == 'b' && comment.charAt(i + 1) == 'a' && comment.charAt(i + 2) == 'd')
{
System.out.print("bad");
}
else
{
System.out.print("*");


}
}
else
{
System.out.print(" ");

}





}
Richard Deeming 24-Feb-23 7:37am    
You'll also need to add 2 to the loop index when you find "bad".
if (i < comment.length() - 2 && comment.charAt(i) == 'b' && comment.charAt(i + 1) == 'a' && comment.charAt(i + 2) == 'd')
{
    System.out.print("bad");
    i += 2;
}
Abhinav Kishore M 24-Feb-23 7:43am    
Thanks Richard but even though I am getting bad and words have been replaced by equal number of *, I am also getting o/p as under:
* ** badI am bad
The sentence is repeated again.
How to resolve this issue?
Additional to what Richard wrote, I suggest chunking the string: How to Split a String in Java with Delimiter - Javatpoint[^] and doing word comparisons, then rejoining/concatenating.

How to compare words: String Comparison in Java - javatpoint[^]
 
Share this answer
 
v2
Comments
Abhinav Kishore M 24-Feb-23 6:56am    
Did u mean this:
if(comment.charAt(i)!=' ')
{
    String s1="bad";
    if(s1==comment.substring(i, i+3))
    {
        System.out.print(s1);
    }
    else 
    {
        System.out.print("*");
     }
 }    
else
{
    System.out.print(" ");
}
Graeme_Grant 24-Feb-23 7:08am    
I am not going to write it for you, however here is the logic:

1. Split the words in an array
2. loop over each word and compare with "bad"
3. if not equals bad, replace word with equal number of '*'
4. concat/join result string (result = result + word + " ")
5. go to 2.
6. print result

ps: take the time to read the content in the link that I provided for you.
Abhinav Kishore M 24-Feb-23 7:30am    
I have resolved this issue as under:
for (int i = 0; i < comment.length(); i++) {

if(comment.charAt(i)!=' ')
{


if (i < comment.length() - 2 && comment.charAt(i) == 'b' && comment.charAt(i + 1) == 'a' && comment.charAt(i + 2) == 'd')
{
System.out.print("bad");
}
else
{
System.out.print("*");


}
}
else
{
System.out.print(" ");

}





}
But now o/p is coming as under:
* ** bad**I am bad
Abhinav Kishore M 24-Feb-23 8:14am    
Hi I wrote this code correctly and for many inputs it was showing correct o/p. But for this i/p:
Bad code is being shown. Bad comment is not to be shown. How many bad is there?
It is showing o/p as:
*** **** ** ***** ****** *** ******* ** *** ** ** ****** *** **** ** *bad* ******
Can we make this code possible for ALL inputs?

Looks like the other bad is being replaced by *. No idea why?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900