Printing *s as triangles in Java?

后端 未结 21 1908
囚心锁ツ
囚心锁ツ 2020-11-30 11:41

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

21条回答
  •  臣服心动
    2020-11-30 12:17

    This is the least complex program, which takes only 1 for loop to print the triangle. This works only for the center triangle, but small tweaking would make it work for other's as well -

    import java.io.DataInputStream;
    
    public class Triangle {
        public static void main(String a[]) throws Exception{
            DataInputStream in = new DataInputStream(System.in);
    
            int n = Integer.parseInt(in.readLine());
            String b = new String(new char[n]).replaceAll("\0", " ");
            String s = "*";
            for(int i=1; i<=n; i++){
                System.out.print(b);
                System.out.println(s);
                s += "**";
                b = b.substring(0, n-i);
                System.out.println();
            }
        }
    }
    

提交回复
热议问题