2014-10-18 65 views
2

我想为我的计算机科学课做一些作业,我似乎无法弄清楚这一点。现在的问题是:String.replace()方法没有在java中打印完整的字符串

编写一个程序,读取一行文本,然后显示该行,但随着第一次出现讨厌改为

这听起来像一个基本的问题,所以我继续写这件事:

import java.util.Scanner; 

public class question { 

    public static void main(String[] args) 
    { 
     Scanner keyboard = new Scanner(System.in); 
     System.out.println("Enter a line of text:"); 

     String text = keyboard.next(); 

     System.out.println("I have rephrased that line to read:"); 
     System.out.println(text.replaceFirst("hate", "love")); 
    } 
} 

我期待的“我恨你”的字符串输入改为“我爱你”,但所有它的输出是“I”。当它检测到我想要替换的单词的第一次出现时,它将删除该字符串的其余部分,除非它是该字符串的第一个单词。例如,如果我只是输入“憎恨”,它会改变为“爱”。我看过很多网站和文档,我相信我会遵循正确的步骤。如果任何人都可以解释我在这里做错了什么,这样它就可以用替换的词显示完整的字符串,那太棒了。

谢谢!

回答

1

尝试获得,而不只是第一个标记整条生产线是这样,:

String text = keyboard.nextLine(); 
2

你的错误是在keyboard.next()通话。这会读取第一个(空格分隔的)单词。您想要使用keyboard.nextLine(),因为它读取整行(这是您的输入在这种情况下)。

修,你的代码看起来是这样的:

import java.util.Scanner; 

public class question { 

    public static void main(String[] args) 
    { 
     Scanner keyboard = new Scanner(System.in); 
     System.out.println("Enter a line of text:"); 

     String text = keyboard.nextLine(); 

     System.out.println("I have rephrased that line to read:"); 
     System.out.println(text.replaceFirst("hate", "love")); 
    } 
} 
1

keyboard.next()只读取下一个标记。 使用keyboard.nextLine()来读取整个行。

在您当前的代码中,如果您在replace之前打印text的内容,您将看到只有I已被作为输入。

0

作为备选答案,建立一个while循环,并在问题查找单词:

import java.util.Scanner; 

public class question { 

public static void main(String[] args) 
{ 
     // Start with the word we want to replace 
     String findStr = "hate"; 
     // and the word we will replace it with 
     String replaceStr = "love"; 
     // Need a place to put the response 
     StringBuilder response = new StringBuilder(); 
     Scanner keyboard = new Scanner(System.in); 
     System.out.println("Enter a line of text:"); 
     System.out.println("<Remember to end the stream with Ctrl-Z>"); 

     String text = null; 
     while(keyboard.hasNext()) 
     { 
      // Make sure we have a space between characters 
      if(text != null) 
      { 
      response.append(' '); 
      } 
      text = keyboard.next(); 
      if(findStr.compareToIgnoreCase(text)==0) 
      { 
      // Found the word so replace it 
      response.append(replaceStr); 
      } 
      else 
      { 
      // Otherwise just return what was entered. 
      response.append(text); 
      } 
     } 

     System.out.println("I have rephrased that line to read:"); 
     System.out.println(response.toString()); 
    } 
} 

注意到扫描仪在同一时间返回一个单词的优势。如果该单词后面跟着标点符号,则匹配将失败。无论如何,当我读到这个问题时,这是我脑海中浮现的答案。

相关问题