英文:
How to correct this text processing programme?
问题
import java.util.Scanner;
public class TextProcessing {
public static void main(String[] args) {
String sentence, wordToBeTargeted, wordToBeReplaced, output;
boolean wordToCheck;
Scanner myInput = new Scanner(System.in);
sentence = myInput.nextLine();
do {
wordToCheck = true;
System.out.println("Please enter the word for replacement:");
wordToBeTargeted = myInput.nextLine();
if (sentence.toLowerCase().indexOf(wordToBeTargeted.toLowerCase()) == -1) {
wordToCheck = false;
System.out.println("This word cannot be found in the sentence!");
} else {
System.out.println("Please enter the word you would like to replace with:");
wordToBeReplaced = myInput.nextLine();
sentence = sentence.replaceAll("(?i)" + wordToBeTargeted, wordToBeReplaced);
System.out.println(sentence);
}
} while (wordToCheck == false);
}
}
英文:
import java.util.Scanner;
public class TextProcessing
{
public static void main(String[] args)
{
String sentence, wordToBeTargeted, wordToBeReplaced, output;
boolean wordToCheck;
Scanner myInput = new Scanner(System.in);
sentence = myInput.nextLine();
do
{
wordToCheck = true;
System.out.println("Please enter the word for replacement:");
wordToBeTargeted = myInput.nextLine;
if(sentence.toLowerCase().indexOf(wordToBeTargeted.toLowerCase()) == -1)
{
wordToCheck = false;
System.out.println("This word cannot be found in the sentence!")
}
else
{
System.out.println("Please enter the word you would like to replace with:");
wordToBeReplaced = myInput.nextLine();
}
}while(wordToCheck = false);
}
}
}
Write a file named TextProcessing.java that will replace all occurrences of a word in a string with another word
The expected outcome is like this:
答案1
得分: 1
我不会将代码写出来 - 你仍然应该从这个练习中获益,但会给予一些方向。脑海中首先浮现的方法是:
- 将第一个输入按照 ' ' 进行分割成一个列表
- 遍历列表,根据两个输入字符串有条件地更改值
- 在遍历时,根据要求,你可以将输出放入一个新的字符串/字符串生成器,或直接写入控制台。
英文:
I won't write the code out - you should still get something out of the exercise, but will give some direction. The first approach that comes to mind:
- Split the first input on ' ' into a list
- Iterate through the list, conditionally changing values based based on two input strings
- As you're iterating you can either output into a new string / stringbuilder, or directly write to console depending on the requirements
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论