replaceAll方法对我不起作用我在做什么错?

时间:2019-02-08 14:07:58

标签: java string replaceall

我运行了代码,但是它没有将string1替换为string2

我尝试梳理扫描仪,但是没有用。我试着分别关闭扫描仪,但结果当然是语法错误。

import java.util.*;
public class Remove_and_Replace {
public static void main(String []args) {
      Scanner a = new Scanner(System.in);
      System.out.println("Enter your first word:");
      String String1 = a.nextLine();
      Scanner b = new Scanner(System.in);
      System.out.println("Enter your second word:");
      String String2 = b.nextLine();
      Scanner c = new Scanner(System.in);
      System.out.println("Enter your sentence:");
      String String3 = c.nextLine();
      c.close();

      String replaceString=String3.replaceAll("String1","String2");
     System.out.println(replaceString); 
    }
}

预期结果:

Enter your first word:
bad
Enter your second word:
good
Enter your sentence:
I am always bad.
I am always good.

实际结果:

Enter your first word:
bad
Enter your second word:
good
Enter your sentence:
I am always bad.
I am always bad.

5 个答案:

答案 0 :(得分:0)

删除双引号:

  String replaceString=String3.replaceAll(String1, String2);

说明

在原始行中,您将 String 从字面上替换为 String2 。如果不使用双引号,则将String1变量(坏)中存储的单词替换为String2变量(好)中存储的单词。附带说明一下,Java命名约定指定变量以小写字母开头-大写用于

答案 1 :(得分:0)

此行:

String replaceString=String3.replaceAll("String1","String2");

应替换为:

String replaceString=String3.replaceAll(String1, String2);

在第一行中,您尝试替换值“ String1”本身,而不是使用对象。

答案 2 :(得分:0)

为什么在引号中使用String1,String2?

替换此:

  String replaceString=String3.replaceAll("String1","String2");

与此:

  String replaceString=String3.replaceAll(String1,String2);

顺便说一句,根据命名约定,变量始终以小写字母开头。因此应该看起来像:

public static void main(String[] args) {
    Scanner a = new Scanner(System.in);
    System.out.println("Enter your first word:");
    String firstWord = a.nextLine();
    Scanner b = new Scanner(System.in);
    System.out.println("Enter your second word:");
    String secondWord = b.nextLine();
    Scanner c = new Scanner(System.in);
    System.out.println("Enter your sentence:");
    String sentence = c.nextLine();
    c.close();

    String updatedSentence = sentence.replaceAll(firstWord, secondWord);
    System.out.println(updatedSentence);
}

您可以在此处阅读更多内容:https://www.javatpoint.com/java-naming-conventions

答案 3 :(得分:0)

您需要从方法中删除引号。发生的事情是它正在寻找单词“ String1”,如果找到所说的单词,它将用单词“ String2”代替。删除引号使它可以查找对象的引用,而不是实际的变量名。

此:String replaceString=String3.replaceAll("String1", "String2");

应变为:String replaceString=String3.replaceAll(String1,String2);

答案 4 :(得分:-2)

String replaceString = String3.replaceAll(String1,String2);

像这样更改并打印替换字符串,您会得到答案