java输出可变行等腰杨辉三角形拜托各位大神
如何修改使得可输出为等腰杨辉三角形importjava.util.Scanner;publicclassYangHui{publicstaticvoidmain(Stri...
如何修改使得可输出为等腰杨辉三角形 import java.util.Scanner; public class YangHui { public static void main(String[] args) { int row = getInt("请输入需要打印的行数(1-20): "); int[][] a = new int[row][row]; for (int i = 0; i < row; i++) for (int j = 0; j < row; j++) { if (j < i) { a[i][j] = 1; if (j == 0) { a[i][j] = 1; } else { a[i][j] = a[i - 1][j - 1] + a[i - 1][j]; } } else { a[i][j] = 1; } } for (int i = 0; i < row; i++) { for (int j = 0; j <= i; j++) { System.out.print(a[i][j]); } System.out.print("\n"); } } /** * 这里判断是不是输入非数字并且行数应该在1-20行之内 * * @param tip * @return */ public static int getInt(String tip) { int row = 0; try { System.out.print(tip); Scanner sc = new Scanner(System.in); row = sc.nextInt(); } catch (Exception e) { System.out.println("输入有误"); row = getInt(tip); } if (row < 1 || row > 20) { System.out.println("输入有误"); row = getInt(tip); } return row; } }
展开
展开全部
import java.util.*; class Demo1 { /*1.打印如图所示的杨辉三角,要求打印出n行,n由键盘输入 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 */ public static void main(String[] args) { System.out.println("请输入要打印的行数:"); Scanner input = new Scanner (System.in); int rows = input.nextInt(); int [][]a = new int [rows][rows]; for (int i =0;i<rows ;i++ ) { for (int j=0;j<=i ;j++ ) { a[i][j] = 1; } } for (int i = 2;i<rows ;i++ ) { for (int j=1;j<i ;j++ ) { a[i][j]=a[i-1][j]+a[i-1][j-1]; } } for (int i = 0;i<rows ;i++ ) { for (int j = 0;j<=i ;j++ ) { System.out.print(a[i][j]+" "); } System.out.println(); } } } 这是本人做的程序,测试了一下, 应该没有错误 行输入可控制 很荣幸为您解答 望楼主采纳!!
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询