Как заменить слово в строке сообщения? - PullRequest
0 голосов
/ 26 июня 2019

Я уже давно пробую несколько разных кодов. При попытке заменить слово говорит, что мой код замены неправильный. Как я могу заменить все слова в сообщениях?

public class StorySynthesiser {

    public static void main(String[] args) {

        String message;
        String name ="Tiger";
        String result = message.replaceAll("Hare", name);


        message = "";
        message = message +"There once was a speedy Hare who bragged about how fast he could run.\n";
        message = message +"Tired of hearing him boast, the Tortoise challenged him to a race.\n";
        message = message +"All the animals in the forest gathered to watch.\n";
        message = message +"The Hare ran down the road for a while and then paused to rest. \n";
        message = message +"He looked back at the tortoise and cried out, \"How do you expect to win this race when you are walking along at your slow, slow pace?\n";
        message = message +"The Tortoise walked and walked, never ever stopping until he came to the finish line.\n";       
        message = message +"The animals who were watching cheered so loudly for Tortoise that they woke up the Hare. The Hare stretched, yawned and began to run again, but it was too late.\n";
        message = message +"Tortoise had already crossed the finish line in 2 hours ago/n";



        JOptionPane.showMessageDialog(null, message);

Ответы [ 6 ]

1 голос
/ 26 июня 2019

В этом коде при вызове replaceAll сообщение имеет значение null.Вы должны позвонить после присвоения.

 String message = "";
String name ="Tiger";


message += "There once was a speedy Hare who bragged about how fast he could run.\n";
message += "Tired of hearing him boast, the Tortoise challenged him to a race.\n";
message += "All the animals in the forest gathered to watch.\n";
message += "The Hare ran down the road for a while and then paused to rest. \n";
message += "He looked back at the tortoise and cried out, \"How do you expect to win this race when you are walking along at your slow, slow pace?\n";
message += "The Tortoise walked and walked, never ever stopping until he came to the finish line.\n";       
message += "The animals who were watching cheered so loudly for Tortoise that they woke up the Hare. The Hare stretched, yawned and began to run again, but it was too late.\n";
message += "Tortoise had already crossed the finish line in 2 hours ago/n";


String result = message.replaceAll("Hare", name);
JOptionPane.showMessageDialog(null, result);
1 голос
/ 26 июня 2019

Вы заменяете сначала и присваиваете значения позже, а также отображаете другую переменную в вашем DialogPane, поэтому вам нужно сделать это следующим образом:

    String name ="Tiger";


    message = "";
    message = message +"There once was a speedy Hare who bragged about how fast he could run.\n";
    message = message +"Tired of hearing him boast, the Tortoise challenged him to a race.\n";
    message = message +"All the animals in the forest gathered to watch.\n";
    message = message +"The Hare ran down the road for a while and then paused to rest. \n";
    message = message +"He looked back at the tortoise and cried out, \"How do you expect to win this race when you are walking along at your slow, slow pace?\n";
    message = message +"The Tortoise walked and walked, never ever stopping until he came to the finish line.\n";       
    message = message +"The animals who were watching cheered so loudly for Tortoise that they woke up the Hare. The Hare stretched, yawned and began to run again, but it was too late.\n";
    message = message +"Tortoise had already crossed the finish line in 2 hours ago/n";

   String result = message.replaceAll("Hare", name);

    JOptionPane.showMessageDialog(null, result);
0 голосов
/ 26 июня 2019

Вы заменяете строку перед установкой сообщения.Попробуйте изменить порядок:

        String message; //message is now null, trying to replace will cause a Null pointer exception.
        String name ="Tiger";


        message = ""; //message is now an empty string, replaceing something will be useless as there is nothing there.
        message = message +"There once was a speedy Hare who bragged about how fast he could run.\n";
        message = message +"Tired of hearing him boast, the Tortoise challenged him to a race.\n";
        message = message +"All the animals in the forest gathered to watch.\n";
        message = message +"The Hare ran down the road for a while and then paused to rest. \n";
        message = message +"He looked back at the tortoise and cried out, \"How do you expect to win this race when you are walking along at your slow, slow pace?\n";
        message = message +"The Tortoise walked and walked, never ever stopping until he came to the finish line.\n";       
        message = message +"The animals who were watching cheered so loudly for Tortoise that they woke up the Hare. The Hare stretched, yawned and began to run again, but it was too late.\n";
        message = message +"Tortoise had already crossed the finish line in 2 hours ago/n";


        //here message is full and has some "Hare" to replace.
        String result = message.replaceAll("Hare", name);


        JOptionPane.showMessageDialog(null, message);

Проверьте этот не по теме совет:

message = message + "hello";

совпадает с:

message += "hello";
0 голосов
/ 26 июня 2019

Вы должны инициализировать переменную message во время объявления, так как все это синхронно, вы должны поставить replaceAll после добавления в переменную message, в противном случае вы получите пустую строку.

    public class StorySynthesiser  {

    public static void main(String[] args) {

        String message=""; // initailize your message here
        String name ="Tiger";
        message = message +"There once was a speedy Hare who bragged about how fast he could run.\n";
        message = message +"Tired of hearing him boast, the Tortoise challenged him to a race.\n";
        message = message +"All the animals in the forest gathered to watch.\n";
        message = message +"The Hare ran down the road for a while and then paused to rest. \n";
        message = message +"He looked back at the tortoise and cried out, \"How do you expect to win this race when you are walking along at your slow, slow pace?\n";
        message = message +"The Tortoise walked and walked, never ever stopping until he came to the finish line.\n";       
        message = message +"The animals who were watching cheered so loudly for Tortoise that they woke up the Hare. The Hare stretched, yawned and began to run again, but it was too late.\n";
        message = message +"Tortoise had already crossed the finish line in 2 hours ago/n";
String result = message.replaceAll("Hare", name);
    System.out.println(result);

    }}

Рабочая repl

0 голосов
/ 26 июня 2019

Здесь нужно изменить две вещи

Инициализировать переменную

   String message;

и вызвать заменить в конце, как показано ниже.

    String message = "";
    String name ="Tiger";


    message = message +"There once was a speedy Hare who bragged about how fast he could run.\n";
    message = message +"Tired of hearing him boast, the Tortoise challenged him to a race.\n";
    message = message +"All the animals in the forest gathered to watch.\n";
    message = message +"The Hare ran down the road for a while and then paused to rest. \n";
    message = message +"He looked back at the tortoise and cried out, \"How do you expect to win this race when you are walking along at your slow, slow pace?\n";
    message = message +"The Tortoise walked and walked, never ever stopping until he came to the finish line.\n";       
    message = message +"The animals who were watching cheered so loudly for Tortoise that they woke up the Hare. The Hare stretched, yawned and began to run again, but it was too late.\n";
    message = message +"Tortoise had already crossed the finish line in 2 hours ago/n";

    String result = message.replaceAll("Hare", name);


    JOptionPane.showMessageDialog(null, message);
0 голосов
/ 26 июня 2019

Вам необходимо выполнить замену после , когда вы фактически присвоили сообщение:

String message = "content here...";
String result = message.replaceAll("Hare", name);

Обратите внимание, что поскольку вы на самом деле не выполняете замену регулярных выражений, вы можете просто использовать String#replace здесь для повышения производительности:

String result = message.replace("Hare", name);
...