• Post Reply Bookmark Topic Watch Topic
  • New Topic

Please help!! Replace word  RSS feed

 
Sarah Tod
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I am trying to replace the word "Hate" to "Love". But my program did not print the last word of the sentence. Please advise me what i am missing. Thank you so much!
Here is my program:

import java.util.Scanner;

public class HateLove
{
public static void main(String[] args)
{
System.out.println("Enter line of text.");

Scanner kb = new Scanner(System.in);

String s = kb.next();

int hates = s.indexOf("");

System.out.println(s);

s = s.substring(hates) + " loves ";


System.out.println("I have rephrased that line to read:");

System.out.println(s);

}
}
 
Ishan Pandya
Ranch Hand
Posts: 228
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And what kind of input you are giving from console?

try looking at the method called replaceAll() in String Class.. try looking at it into the docs.
 
Mansukhdeep Thind
Ranch Hand
Posts: 1163
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the ranch.

Anyways, first of all make sure you use code tags whenever you paste code:



Also, use proper indentation. See how much clear it is now. I don't quite understand your logic though. I can provide you with a hint of how to go about your task. There is a method already provided in String class for this very purpose. Read this

P.S--> What is your name ? SD or TD? Please use a proper name.
 
Campbell Ritchie
Marshal
Posts: 56576
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome again
I would suggest you learn about StringBuilder (←link) and use its method to remove and insert those words. Then use its toString method to get it back to a String.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!