• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 197
  • Last Modified:

JAVA programming problem

I need help writing a script where a user can input values via keyboard, lets say the user enters " I hate to hate you".  The script should echo what the user wrote, then echo and change the first "hate" to "love".  Only the first hate can change, no matter how many "hate" exist.

The final output should look like " I love to hate you"

If you can solve this one... you are truly a programming god!
0
angeljava
Asked:
angeljava
  • 2
1 Solution
 
bobbit31Commented:
import java.io.*;

public class Example {

     public static void main(String[] args) {
          String text = null;

          try {
               System.out.print("Enter text: ");
               BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

               if ((text = in.readLine()) != null) {
                    int ix = text.indexOf("hate");
                    if (ix != -1) {
                         text = text.substring(0, ix) + "love" + text.substring(ix+4);
                    }
                    System.out.println(text);
               }

               in.close();
          } catch (Exception e) {
               e.printStackTrace();
          }

     }

}
0
 
umangjoshiCommented:
String text = "I hate to hate you";
String newText = new String();

int pos = text.indexOf("hate");
if (pos != -1)
{
   newText = text.substring(0,pos);
   newText = newText + text.substring(pos+4);
   System.out.println(newText);
}
else
{
   System.out.println("Not found");
}
0
 
umangjoshiCommented:
String text = "I hate to hate you";
String newText = new String();

int pos = text.indexOf("hate");
if (pos != -1)
{
  newText = text.substring(0,pos);
  newText = newText + " love " + text.substring(pos+4);
  System.out.println(newText);
}
else
{
  System.out.println("Not found");
}
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now