fucorogu fucorogu -3 years ago 82
Java Question

Replace a word in string if it is found in an array

For example the user types: The fruit apple is my favourite.
I'd like to return: The fruit ***** is my favourite.

But my code only returns the first word.

public static void main(String[] args) {
System.out.print("Type someting: ");
Scanner scan = new Scanner(System.in);
String s = scan.next();

String [] myArray = {"apple", "banana", "strawberry"};
boolean matchFound = false;

for (int i = 0; i < myArray.length; i++) {
if (s.toLowerCase().contains(myArray[i].toLowerCase())){
String beep = String.join("", Collections.nCopies(myArray[i].length(), "*"));
String result = s.replaceAll(myArray[i].toLowerCase(), beep);

matchFound = true;


if (matchFound == false){


Answer Source

Way of inputting is not correct

It should be

String s = scan.nextLine();

rather than scan.next();

With s = scan.next();

s will only get initialized as "The"

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download