I am writing a program where if someone types in the following two lines:
HELLO, I’D LIKE TO ORDER A FZGH
KID’S MEAL
The program will output it like this:
HELLO, I’D LIKE TO ORDER A KID’S MEAL
In other words, the “FZGH” the user inputs into the sentence will be replaced with the second line’s words, as you can see: the “FZGH” is replaced by “KID’S MEAL.” Kinda get what I mean? If not, I can elaborate more but this is the best I can explain it as.
I’m really close to solving this! My current output is: HELLO, I’D LIKE TO ORDER A FZGH KID’S MEAL
My program didn’t replace the “FZGH” with “KID’S MEAL,” and I don’t know why that is. I thought that by using the .replaceAll() thingy, it would replace “FZGH” with the “KID’S MEAL,” but that didn’t really happen. Here is my program so far:
public static void main(String[] args) {
sentences();
}
public static void sentences() {
Scanner console = new Scanner(System.in);
String sentence1 = console.nextLine();
String sentence2 = console.nextLine();
//System.out.println(sentence1 + "\n" + sentence2);
String word = sentence1.replaceAll("[FZGH]", "");
word = sentence2;
System.out.print(sentence1 + word);
}
Where did I mess up, resulting in the FZGH still appearing in output?
Use
Your first (and primary) problem is that you’re creating a new
Stringnamedword, that you’re setting to the value ofsentence1.replaceAll("[FZGH]", ""). You’re then changing the value ofwordto besentence2immediately afterward, so the replacement is lost.Instead, setting
sentence1tosentence1.replaceAll("FZGH", "");will changesentence1to no longer contain the string"FZGH", which is what you’re going for. You don’t actually need awordvalue at all, so if you’d like to remove it, it wouldn’t hurt.In addition, using
[FZGH]will replace allF‘s,Z‘s,G‘s, andH‘s from the string- you should useFZGHinstead, as this will only remove instances of all four letters in a row.