Text to HTML Learn programming Java



Lesson:

OOP More On Classes


Exercise:

Text to HTML


Objetive:

Create a class "TextToHTML", which must be able to convert several texts entered by the user into a HTML sequence, like this one:

Hola
Soy yo
Ya he terminado

should become

Hola

Soy yo

Ya he terminado

The class must contain:
An array of strings
A method "Add", to include a new string in it
A method "Display", to show its contents on screen
A method "ToString", to return a string containing all the texts, separated by "\n".
Create also an auxiliary class containing a "Main" function, to help you test it.


Code:

public class TextToHTML
{
    protected String[] myHTML;
	protected int maxLines = 1000;
	private int counter = 0;

	public TextToHTML()
	{
		myHTML = new String[maxLines];
	}

	public final void Add(String newSentence)
	{
		if (counter < maxLines)
		{
			myHTML[counter] = newSentence;
			counter++;
		}
	}

	public final String toString()
	{
		String allHTML = "\n\n";

		for (int i = 0; i < counter; i++)
		{
			allHTML += myHTML[i]; allHTML += "\n";
		}

		allHTML += "\n";
		allHTML += "\n";

		return allHTML;
	}

	public final void Display()
	{
		System.out.print(toString());
	}

}

public class Main
{
	public static void main(String[] args)
	{
		TextToHTML example = new TextToHTML();
		example.Add("Hola");
		example.Add("uno dos");
		example.Add("tres cuatro");
		example.Display();
	}
}



Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.