java列印等腰三角形的兩種方法!(根據行數,根據底邊長度)

來源:互聯網
上載者:User

標籤:system   ack   print   先來   使用者輸入   inpu   src   string   iso   

首先來看根據使用者輸入的底邊的長度判斷:

 1 package cn.edu.nwpu.java; 2  3 import java.util.Scanner; 4  5 public class IsoscelesTriangle { 6  7     public static void main(String[] args) { 8         // 列印輸出等腰三角形 9         System.out.println("請輸入等腰三角形的底邊長度:");10         while (true) {11             Scanner input = new Scanner(System.in);12             String result = input.next();13             int number = Integer.valueOf(result);14             if (number >= 3) {15                 System.out.println("=======從這裡開始測試======");16                 for(int i = 1; i <= (number+1)/2; i++) {17                     for(int m = 1; m <= (number+1)/2-i; m++ ) {18                         System.out.print(" ");19                     }20                     for(int j = 1; j <= 2*i-1; j++) {21                         System.out.print("*");22                     }23                     System.out.println();24                 }25             } else {26                 System.out.println("數字不能小於3,請重新輸入:");27             }28         }29     }30 }

再來看看第二種方法,輸入行號,輸出三角形(這個就簡單一些了):

 1 package cn.edu.nwpu.java; 2  3 import java.util.Scanner; 4  5 public class IsoscelesTriangle { 6  7     public static void main(String[] args) { 8         // 列印輸出等腰三角形 9         System.out.println("請輸入等腰三角形的行數:");10         while (true) {11             Scanner input = new Scanner(System.in);12             String result = input.next();13             int number = Integer.valueOf(result);14             System.out.println("=======從這裡開始測試======");15             for (int i = 1; i <= number; i++) {16                 for (int m = 1; m <= number - i; m++) {17                     System.out.print(" ");18                 }19                 for (int j = 1; j <= 2 * i - 1; j++) {20                     System.out.print("*");21                 }22                 System.out.println();23             }24         }25     }26 }

執行如,這個文章的經典在第一個例子,裡面的規律想起來比較頭疼!

java列印等腰三角形的兩種方法!(根據行數,根據底邊長度)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.