Centered triangle Learn programming Java

Lesson:

Arrays, Structures and Strings


Exercise:

Centered triangle 12


Objetive:

Display a centered triangle from a string entered by the user:

__a__
_uan_
Juan


Code:

import java.util.*;
public class Main
{
	public static void main(String[] args)
	{
		String name;

		System.out.print("Enter your name: ");
		name = new Scanner(System.in).nextLine();

		if (name.length() % 2 == 0)
		{
			name += " ";
		}

		int position = name.length() / 2;
		int maxRows = name.length() / 2 + 1;
		int amount = 1;

		for (int i = 0; i < maxRows; i++)
		{
			for (int j = 0; j < position; j++)
			{
				System.out.print(" ");
			}
			System.out.println(name.substring(position, position + amount));
			position--;
			amount += 2;
		}
	}
}