Help with a program that replaces words

1

I have to do the following exercise in Java with Eclipse:

  

Write a Java program that first reads two words from the console: the first will be called the pattern and the second substitution. Then the program will interactively read a series of lines of text from the console until an empty line is read. For each line read, you should analyze if the word pattern is found one or several times, and if this occurs, show the line by changing the word pattern to the word substitution in all occurrences. Before finishing its execution it must show the number of lines in which it has found the word pattern.

The truth is that I do not have much idea of how to cover this program. I thought of something like this:

import java.util.Scanner;

public class palabrasT {
    public static void main(String[]args) {
        String patron;
        String texto;
        String vacia = "";
        int contador = 0;
        Scanner sc = new Scanner(System.in);

        do{
            System.out.println("Introduzca un patron");
            patron = sc.nextLine();
            System.out.println("Introduzca una linea");
            texto = sc.nextLine();
            String array [] = texto.split("");

            for (int i = 0; i<array.length;i++) {
                if(array[i].equals("patron"))
                    System.out.println(texto.replace(patron, texto));
                contador++;
            }
        } while(texto!=null);
        sc.close();
        System.out.println("La palabra patron aparece" +contador + "veces");

    }
}

But when compiling and executing it I get a loop that asks

  

Enter a line

     

Enter a pattern

     

Enter a line

     

...

    
asked by RubénR 07.03.2017 в 20:39
source

1 answer

1

Hello, I'll help you with your problem.

import java.util.Scanner;

public class palabrasT {

  public static void main(String[]args) {

    String patron;      
    String texto;
    String vacia = "";
    int contador = 0;

    Scanner sc = new Scanner(System.in);    
    System.out.println("Introduzca un patron");
    patron = sc.nextLine();
    System.out.println("Introduzca un texto de substitucion");
    texto= sc.nextLine();

    while(sc.hasNext()){
       vacia=sc.nextLine();
       if(vacia.contains(patron)){
           texto=texto.replaceAll(patron,texto);
           contador++; 
       }
    }


    System.out.println("La palabra patron aparece" +contador + "veces");

   }
}

Your problem is that the pattern and the replacement text should be outside the do while. and you need a sentence to read the lines, but with the code that you modify, it works.

    
answered by 07.03.2017 в 20:54