Display four patterns using loops
This was hard and thank you Stack Overflow and textbook! I definitely need more practice here as I had to look so much up!
public class Patterns
{
public static void main(String[] args)
{
//prints pattern title
System.out.println(
"Pattern A");
//starts at one increments up to 6
for (int i = 1; i < 7; i++)
{
/
/stores value in string
String A =
"";
int start = 1;
//starts at 1 and and continues until 6
while(start <= i)
{
//adds each new term to the string and increments
//start by 1
A += start +
" ";
start++;
}
//prints string after each iteration until 7 is reached
System.out.println(A);
}
//places an empty line between patterns
System.out.println();
System.out.println(
"Pattern B");
//loop starts at 6 and decrements to 1
for (
int i = 6; i > 0; i--)
{
String B =
"";
int start = 1;
while (start <= i)
{
B += start +
" ";
start++;
}
System.out.println(B);
}
System.out.println
("Pattern C");
//starts at 1 and runs 6 times
for (
int i = 1; i < 7; i++)
{
String C =
"";
int start = i;
while (start >= 1)
{
//starts at printing 1-6 and decrements
C += start +
" ";
start --;
}
//output the string with a width of at least
//12 spaces and then start a new line
System.out.printf(
"%12s\n", C);
}
System.out.println(
"\nPattern D");
for (
int i = 6, space = 0; i >0; i--)
{
String D = "";
int start = 1;
while(start <= i)
{
D += start +
" ";
start++;
}
System.out.printf(
"%12s\n", D);
}
}
}
I need to study formatting a bit more, so here goes!
%b boolean value true of false
%c character 'a'
%d decimal integer 200
%f floating point number 45.4600000
%e scientific notation 4.556000e+01
%s string "Hello World"
%5c output the character and add four spaces because the width is five
%6b output the Boolean value and add one space before the false and two before true
%5d output integer with a width of at least 5..add spaces before if < 5 increase width if >
%10.2f output floating point, width 10+ and two decimal places (7 allocated before decimal
%10.2e output floating point, width 10+ and two decimal places
%12s output string, width 12+ add spaces if fewer than 12.. increase width if more