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
...