用Java程序来打印正方形的右增量数字图案

190 阅读1分钟

编写一个Java程序,使用for循环打印正方形的右增量数字模式。

package Shapes3;

import java.util.Scanner;

public class SquareRightincNum1 {

private static Scanner sc;

public static void main(String\[\] args) {
	sc = new Scanner(System.in);
	
	System.out.print("Enter Square of Right Increment Numbers Rows = ");
	int rows = sc.nextInt();
	
	System.out.println("Square of Increment Numbers from Right Side");
	
	for (int i = 1; i <= rows; i++ ) 
	{
		for (int j = 1; j <= rows - i; j++ ) 
		{
			System.out.print(1 + " ");
		}
		for(int k = 1; k <= i; k++) 
		{
			System.out.print(i + " ");
		}
		System.out.println();
	}
}

image.png

这个Java程序使用while循环打印右侧增量数字的正方形图案。

package Shapes3.X

import java.util.Scanner;

public class SquareRightincNum2 {

private static Scanner sc;

public static void main(String\[\] args) {
	sc = new Scanner(System.in);
	
	System.out.print("Enter Square of Right Increment Numbers Rows = ");
	int rows = sc.nextInt();
	
	System.out.println("Square of Increment Numbers from Right Side");
	int j, k, i = 1;
	
	while( i <= rows) 
	{
		j = 1;
		while(j <= rows - i ) 
		{
			System.out.print(1 + " ");
			j++;
		}
		
		k = 1;
		while( k <= i) 
		{
			System.out.print(i + " ");
			k++;
		}
		System.out.println();
		i++;
	}
}
Enter Square of Right Increment Numbers Rows = 9
Square of Increment Numbers from Right Side
1 1 1 1 1 1 1 1 1 
1 1 1 1 1 1 1 2 2 
1 1 1 1 1 1 3 3 3 
1 1 1 1 1 4 4 4 4 
1 1 1 1 5 5 5 5 5 
1 1 1 6 6 6 6 6 6 
1 1 7 7 7 7 7 7 7 
1 8 8 8 8 8 8 8 8 
9 9 9 9 9 9 9 9 9 

在这个Java例子中,我们创建了一个squareIncNum函数,它将从右侧显示增量数字的方形图案。

package Shapes3;

import java.util.Scanner;

public class SquareRightincNum3 {

private static Scanner sc;

public static void main(String\[\] args) {
	sc = new Scanner(System.in);
	
	System.out.print("Enter Square of Right Increment Numbers Rows = ");
	int rows = sc.nextInt();
	
	System.out.println("Square of Increment Numbers from Right Side");	
	squareIncNum(rows);
	
}

public static void squareIncNum(int rows)
{
	for (int i = 1; i <= rows; i++ ) 
	{
		for (int j = 1; j <= rows - i; j++ ) 
		{
			System.out.print(1 + " ");
		}
		for(int k = 1; k <= i; k++) 
		{
			System.out.print(i + " ");
		}
		System.out.println();
	}
}
Enter Square of Right Increment Numbers Rows = 5
Square of Increment Numbers from Right Side
1 1 1 1 1 
1 1 1 2 2 
1 1 3 3 3 
1 4 4 4 4 
5 5 5 5 5