Printing *s as triangles in Java?

后端 未结 21 1873
囚心锁ツ
囚心锁ツ 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

    public static void main(String[] args) {
    
        System.out.print("Enter the number: ");
        Scanner userInput = new Scanner(System.in);
        int myNum = userInput.nextInt();
        userInput.close();
    
        System.out.println("Centered Triange");
        for (int i = 1; i <= myNum; i+=1) {//This tells how many lines to print (height)
    
            for (int k = 0; k < (myNum-i); k+=1) {//Prints spaces before the '*'
                System.out.print(" ");
            }
    
            for (int j = 0; j < i; j++) { //Prints a " " followed by '*'.   
                System.out.print(" *");
            }
    
            System.out.println(""); //Next Line     
        }
    
        System.out.println("Left Triange");
        for (int i = 1; i <= myNum; i+=1) {//This tells how many lines to print (height)
    
            for (int j = 0; j < i; j++) { //Prints the '*' first in each line then spaces.  
                System.out.print("* ");
            }
    
            System.out.println(""); //Next Line         
        }
    
        System.out.println("Right Triange");
        for (int i = 1; i <= myNum; i+=1) {//This tells how many lines to print (height)
    
            for (int k = 0; k < (myNum-i); k+=1) {//Prints spaces before the '*'
                System.out.print("  ");
            }
    
            for (int j = 0; j < i; j+=1) { //Prints the " " first in each line then a "*".  
                System.out.print(" *");
            }
    
            System.out.println(""); //Next Line         
        }
    
    }
    

提交回复
热议问题