使用星星打印字母A的Java程序

205 阅读1分钟

写一个Java程序来打印字母A,使用星星的例子。在这个Java字母A图案的例子中,我们使用嵌套的for循环和if语句来打印输出。

package ShapePrograms;

import java.util.Scanner;

public class AlphabetA { private static Scanner sc;

public static void main(String\[\] args) {
	
	sc = new Scanner(System.in);	
	
	System.out.print("Please Enter the Number =  ");
	int rows = sc.nextInt();
	
	System.out.println("---- Printing Alphabet A ------");
	
	for (int i = 0 ; i < rows; i++ ) 
	{
		for (int j = 0 ; j <= rows/2; j++ ) 
		{
			if((i == 0 && j != 0 && j != rows/2) || i == rows / 2 ||
					(j == 0 || j == rows /2 ) && i != 0)
				System.out.print("\*");
			else
				System.out.print(" ");
		}
		System.out.println("\\n");
	}
}

image.png

在这个使用星星图案的Java字母A的例子中,我们用一个while循环代替了for循环。

package ShapePrograms;

import java.util.Scanner;

public class AlphabetA2 { private static Scanner sc;

public static void main(String\[\] args) {
	
	sc = new Scanner(System.in);	
	
	System.out.print("Please Enter the Number =  ");
	int rows = sc.nextInt();
	
	System.out.println("---- Printing Alphabet A ------");
	
	int j, i = 0;
	
	while ( i < rows ) 
	{
		j = 0 ;
		
		while ( j <= rows/2) 
		{
			if((i == 0 && j != 0 && j != rows/2) || i == rows / 2 ||
					(j == 0 || j == rows /2 ) && i != 0)
				System.out.print("\*");
			else
				System.out.print(" ");
			j++;
		}
		System.out.println("\\n");
		i++;
	}
}
Please Enter the Number =  7
---- Printing Alphabet A ------
 ** 

*  *

*  *

****

*  *

*  *

*  *

使用星星打印字母A的Java程序,使用do while循环。

package ShapePrograms;

import java.util.Scanner;

public class AlphabetA3 { private static Scanner sc;

public static void main(String\[\] args) {
	
	sc = new Scanner(System.in);	
	
	System.out.print("Please Enter the Number =  ");
	int rows = sc.nextInt();
	
	System.out.println("---- Printing Alphabet A ------");
	
	int j, i = 0;
	
	do
	{
		j = 0 ;
		
		do
		{
			if((i == 0 && j != 0 && j != rows/2) || i == rows / 2 ||
					(j == 0 || j == rows /2 ) && i != 0)
				System.out.print("\*");
			else
				System.out.print(" ");
			
		} while ( ++j <= rows/2);
		
		System.out.println("\\n");

	} while ( ++i < rows ) ;
}
Please Enter the Number =  10
---- Printing Alphabet A ------
 **** 

*    *

*    *

*    *

*    *

******

*    *

*    *

*    *

*    *