Function WriteTitle Learn programming Java



Lesson:

Functions


Exercise:

Function WriteTitle


Objetive:

Create a function named "WriteTitle" to write a text centered on screen, uppercase, with extra spaces and with a line over it and another line under it:

WriteTitle("Welcome!");

would write on screen (centered on 80 columns):

--------------- W E L C O M E ! ---------------

(Obviously, the number of hyphens should depend on the length of the text).


Code:

import java.util.*;
public class Main
{
	public static void WriteTitle(String text)
	{
		int numOfSpaces = (80 - text.length() * 2) / 2;
		text = text.toUpperCase();

		// Upper line
		for (int i = 0; i < numOfSpaces; i++)
		{
			System.out.print(" ");
		}
		for (int i = 0; i < text.length() * 2 - 1; i++)
		{
			System.out.print("-");
		}
		System.out.println();

		// Real title
		for (int i = 0; i < numOfSpaces; i++)
		{
			System.out.print(" ");
		}
		for (int i = 0; i < text.length(); i++)
		{
			System.out.print(text.charAt(i) + " ");
		}
		System.out.println();

		// Lower line
		for (int i = 0; i < numOfSpaces; i++)
		{
			System.out.print(" ");
		}
		for (int i = 0; i < text.length() * 2 - 1; i++)
		{
			System.out.print("-");
		}
		System.out.println();
	}

	public static void main(String[] args)
	{
		WriteTitle("Welcome!");

		System.out.println("Enter a text: ");
		String text = new Scanner(System.in).nextLine();
		WriteTitle(text);
	}
}



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