In this code, I am trying to replace a letter from a String entered by a user. For example, the program asks for a word, and the user enters "hello", the next variable that the user inputs is the letter that is going to be replaced ("l"), and the final variable is the letter that is going to replace the previous variable ("x").
The result should be "hexxo", but my program is only replacing one of the l's, what is wrong with my program?
import java.util.Scanner;
public class Letter
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter your word:");
String word = input.nextLine();
System.out.println("\nEnter the letter you want to replace:");
String replace = input.nextLine();
System.out.println("\nEnter the replacing letter:");
String add = input.nextLine();
System.out.println(replaceLetter(word, replace, add));
}
public static String replaceLetter(String word, String letterToReplace, String add)
{
String newWord = "";
for(int i = 0; i < word.length(); i++)
{
if(word.substring(i, i+1).equals(letterToReplace))
{
String front = word.substring(0, word.indexOf(letterToReplace));
String back = word.substring(word.indexOf(letterToReplace)+1);
newWord = front + add + back;
}
}
return newWord;
}
}