0

What I'm trying to do here is have a user input a sentence or some type of string, then have the scanner search through the string to determine if there is an "e" or "E" in there. If the scanner finds either one of those it will replace them with "xyz." If they are not present then it should return "All is good!" The code I have thus far is:

public class Example {
    String userInput;

    Scanner in = new Scanner(System.in);
    System.out.println("Please write a sentence.");
    userInput = in.nextLine();

    System.out.println(userInput.replace("e","xyz"));
    System.out.println(userInput.replace("E","xyz"));

    in.close();
}

As I think you can tell this really just prints the same line twice, once removing a lower case e and the other removing a capital E. I was looking for a way to combine the two replacements and then have it replace and print if it finds an e or just print "All is good!" if there are no "e"s.

Makoto
  • 104,088
  • 27
  • 192
  • 230
Eric W
  • 1
  • 3

3 Answers3

1

You're going to want to look into Pattern and its associate Matcher. This can give you precisely what you want.

While String#replaceAll gives you what you want, it's not entirely semantic; you can certainly replace all of the "e"s with "xyz" and then compare them to see if there was no change, but using Matcher gives you a bit more obvious control over the logic.

We first need to compile a regex, then build a matcher from the compiled regex. If we find a match, we can then replace the strings; otherwise, we can print out our value.

String userInput;

Scanner in = new Scanner(System.in);
System.out.println("Please write a sentence.");
userInput = in.nextLine();
Pattern pattern = Pattern.compile("[eE]");
Matcher matcher = pattern.matcher(userInput);
if(matcher.find()) {
    System.out.println(matcher.replaceAll("xyz"));
} else {
    System.out.println("All is good!");
}
System.out.println(userInput.replaceAll("[eE]","xyz"));

Also, don't close the System.in stream. It's not desirable to close that out in case some other part of your application wants to make use of it, or if you want to make use of it later.

Makoto
  • 104,088
  • 27
  • 192
  • 230
1

This isn't related to Scanner at all really. Trivial approach:

String replaced = userInput.replace("e","xyz").replace("E","xyz");
String out = replaced.equals(userInput) ? "All is good!" : replaced;
System.out.println(out);

Or use replaceAll:

Pattern eE = Pattern.compile("[eE]");
String replaced = eE.matcher(userInput).replaceAll("xyz");
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
-1

Java strings are immutable, so you can't just call replace on userInput and expect it to be modified in place. You need to save the result of the function call.

wachr
  • 1,027
  • 12
  • 12
  • Your advice is sound, but in this case they're only printing out the substitution. There's nowhere for the string to be saved. – Makoto Dec 01 '15 at 23:34