如何纠正这个文本处理程序?

huangapple go评论101阅读模式
英文:

How to correct this text processing programme?

问题

  1. import java.util.Scanner;
  2. public class TextProcessing {
  3. public static void main(String[] args) {
  4. String sentence, wordToBeTargeted, wordToBeReplaced, output;
  5. boolean wordToCheck;
  6. Scanner myInput = new Scanner(System.in);
  7. sentence = myInput.nextLine();
  8. do {
  9. wordToCheck = true;
  10. System.out.println("Please enter the word for replacement:");
  11. wordToBeTargeted = myInput.nextLine();
  12. if (sentence.toLowerCase().indexOf(wordToBeTargeted.toLowerCase()) == -1) {
  13. wordToCheck = false;
  14. System.out.println("This word cannot be found in the sentence!");
  15. } else {
  16. System.out.println("Please enter the word you would like to replace with:");
  17. wordToBeReplaced = myInput.nextLine();
  18. sentence = sentence.replaceAll("(?i)" + wordToBeTargeted, wordToBeReplaced);
  19. System.out.println(sentence);
  20. }
  21. } while (wordToCheck == false);
  22. }
  23. }
英文:
  1. import java.util.Scanner;
  2. public class TextProcessing
  3. {
  4. public static void main(String[] args)
  5. {
  6. String sentence, wordToBeTargeted, wordToBeReplaced, output;
  7. boolean wordToCheck;
  8. Scanner myInput = new Scanner(System.in);
  9. sentence = myInput.nextLine();
  10. do
  11. {
  12. wordToCheck = true;
  13. System.out.println("Please enter the word for replacement:");
  14. wordToBeTargeted = myInput.nextLine;
  15. if(sentence.toLowerCase().indexOf(wordToBeTargeted.toLowerCase()) == -1)
  16. {
  17. wordToCheck = false;
  18. System.out.println("This word cannot be found in the sentence!")
  19. }
  20. else
  21. {
  22. System.out.println("Please enter the word you would like to replace with:");
  23. wordToBeReplaced = myInput.nextLine();
  24. }
  25. }while(wordToCheck = false);
  26. }
  27. }
  28. }

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

我不会将代码写出来 - 你仍然应该从这个练习中获益,但会给予一些方向。脑海中首先浮现的方法是:

  1. 将第一个输入按照 ' ' 进行分割成一个列表
  2. 遍历列表,根据两个输入字符串有条件地更改值
  3. 在遍历时,根据要求,你可以将输出放入一个新的字符串/字符串生成器,或直接写入控制台。
英文:

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:

  1. Split the first input on ' ' into a list
  2. Iterate through the list, conditionally changing values based based on two input strings
  3. As you're iterating you can either output into a new string / stringbuilder, or directly write to console depending on the requirements

huangapple
  • 本文由 发表于 2020年10月7日 01:57:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/64231335.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定