My assignment in my Java course is to make 3 triangles. One left aligned, one right aligned, and one centered. I have to make a menu for what type of triangle and then input
I know this is pretty late but I want to share my solution.
public static void main(String[] args) {
String whatToPrint = "aword";
int strLen = whatToPrint.length(); //var used for auto adjusting the padding
int floors = 8;
for (int f = 1, h = strLen * floors; f < floors * 2; f += 2, h -= strLen) {
for (int k = 1; k < h; k++) {
System.out.print(" ");//padding
}
for (int g = 0; g < f; g++) {
System.out.print(whatToPrint);
}
System.out.println();
}
}
The spaces on the left of the triangle will automatically adjust itself depending on what character or what word you want to print.
if whatToPrint = "x"
and floors = 3
it will print
x
xxx
xxxxx
If there's no automatic adjustment of the spaces, it will look like this (whatToPrint = "xxx"
same floor count)
xxx
xxxxxxxxx
xxxxxxxxxxxxxxx
So I made add a simple code so that it will not happen.
For left half triangle, just change strLen * floors
to strLen * (floors * 2)
and the f +=2
to f++
.
For right half triangle, just remove this loop for (int k = 1; k < h; k++)
or change h
to 0
, if you choose to remove it, don't delete the System.out.print(" ");
.
For left aligned right angle triangle you could try out this simple code in java:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int size=sc.nextInt();
for(int i=0;i<size;i++){
for(int k=1;k<size-i;k++){
System.out.print(" ");
}
for(int j=size;j>=size-i;j--){
System.out.print("#");
}
System.out.println();
}
}
}
well for the triangle , you need to have three loops in place of two , one outer loop to iterate the no of line two parallel loops inside the main loop first loop prints decreasing no of loops second loop prints increasing no of '' well i could give the exact logic as well , but its better if you try first just concentrate how many spaces and how many '' u need in every line relate the no of symbols with loop iterating no of lines and you're done ..... if it bothers more , let me know , i'll explain with logic and code as well