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

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

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

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

  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:

确定