0

我正在编写一个程序,如果有人输入以下两行:

您好,我想订购 FZGH

儿童餐

程序会这样输出:

你好,我想点一份儿童餐

换句话说,用户输入句子的“FZGH”将被替换为第二行的单词,如您所见:“FZGH”被“KID'S MEAL”替换。有点明白我的意思?如果没有,我可以详细说明,但这是我能解释的最好的。

我真的很接近解决这个问题!我当前的输出是:你好,我想订购一份 FZGH 儿童餐

我的程序没有用“KID'S MEAL”替换“FZGH”,我不知道为什么会这样。我认为通过使用 .replaceAll() 东西,它会用“KID'S MEAL”替换“FZGH”,但这并没有真正发生。到目前为止,这是我的程序:

public static void main(String[] args) {
    sentences();
}

public static void sentences() {
    Scanner console = new Scanner(System.in);
    String sentence1 = console.nextLine();
    String sentence2 = console.nextLine();
    //System.out.println(sentence1 + "\n" + sentence2);
    String word = sentence1.replaceAll("[FZGH]", "");
    word = sentence2;
    System.out.print(sentence1 + word);

}

我在哪里搞砸了,导致 FZGH 仍然出现在输出中?

4

4 回答 4

1

我认为你有几个错误。也许以下内容很接近......

public static void main(String[] args) {
    sentences();
}

public static void sentences() {
    Scanner console = new Scanner(System.in);
    String sentence1 = console.nextLine();
    String sentence2 = console.nextLine();
    String sentence3 = sentence1+sentence2;
    String final = sentence3.replaceAll("FZGH", "");
    System.out.print(final);
}
于 2012-12-13T04:56:39.867 回答
1

利用

sentence1 = sentence1.replaceAll("FZGH", "");
String word = sentence2;

您的第一个(也是主要)问题是您正在创建一个新的Stringnamed word,并将其设置为sentence1.replaceAll("[FZGH]", ""). 然后,您立即将 的值更改为word,因此替换丢失了。sentence2

相反,设置sentence1tosentence1.replaceAll("FZGH", "");将更改为sentence1不再包含 string "FZGH",这就是你想要的。你实际上根本不需要一个word值,所以如果你想删除它,它不会受到伤害。

此外, using[FZGH]将替换字符串中的所有F's、Z' Gs 和H's - 您应该FZGH改为使用,因为这只会删除连续所有四个字母的实例。

于 2012-12-13T04:49:29.800 回答
0

实际上replace方法返回一个应该再次分配给sentence1的字符串。您可以运行此代码,它工作正常。公共静态无效主要(字符串[]参数){句子();}

public static void sentences() {
        Scanner console = new Scanner(System.in);
        String sentence1 = "HELLO, I’D LIKE TO ORDER A FZGH";
        String sentence2 = "KID’S MEAL";
        //System.out.println(sentence1 + "\n" + sentence2);
         sentence1 = sentence1.replace("FZGH", "");
       String word = sentence2;
        System.out.print(sentence1 + word);

    }
于 2012-12-13T05:05:22.390 回答
0

您正在重新分配字符串“word”

代替行:

String word = sentence1.replaceAll("[FZGH]", "");
word = sentence2;
System.out.print(sentence1 + word);

使用以下几行

sentence1 = sentence1.replaceAll("[FZGH]", "");
System.out.print(sentence1 + sentence2);
于 2012-12-13T04:53:05.707 回答