Программист написал метод replaceLetter, который подсчитывает сумму Часто в слове присутствует буква. Ваша задача — изменить существующий метод для достижения новой цели.
Вместо того, чтобы подсчитывать экземпляры буквы в строке, напишите программу, которая заменяет все экземпляры одной буквы, кроме первого. с другим. Вам следует напрямую изменить replaceLetter, чтобы эта программа работала. В стартовом коде replaceLetter имеет только два значения параметра. Ваша новая версия должна иметь третий параметр, указывающий, какое строковое значение заменяет существующую букву. Добавьте этот третий параметр в конец списка параметров в заголовке метода.
Например,
Код: Выделить всё
replaceLetter("hello", "l", "y")
returns
"helyo"
Введите слово:
Код: Выделить всё
puppy
Enter the letter to be replaced:
p
Enter the new letter:
d
Подсказка: буквы будут назначены пользователем в виде строковых значений. Обязательно используйте методы String для их сравнения!
Мне удалось вызвать только этот метод в man, но я не знаю, каким будет следующий шаг.
Код: Выделить всё
import java.util.Scanner;
public class Letter
{
public static void main(String[] args)
{
// Ask the user for 3 things: their word, letter they want to replace,
// and replacing letter.
Scanner input = new Scanner(System.in);
System.out.println("Enter a word: ");
String letter = input.nextLine();
System.out.println("Enter the letter to be replaced: ");
String replace = input.nextLine();
System.out.println("Enter the new letter: ");
String newLetter = input.nextLine();
// Call the method replaceLetter and pass all 3 of these items to it for
// string processing.
System.out.println(replaceLetter(letter, replace, newLetter));
}
// Modify this method so that it will take a third parameter from a user --
// the String with which they want to replace letterToReplace
//
// This method should replace all BUT the first occurence of letterToReplace
// You may find .indexOf to be useful, though there are several ways to solve this problem.
// This method should return the modified String.
public static int replaceLetter(String word, String letterToReplace, String newLetter)
{
int count = 0;
for(int i = 0; i < word.length(); i++)
{
if(word.substring(i, i+1).equals(letterToReplace))
{
count++;
}
}
return count;
}
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... rd-in-java
Мобильная версия