编写一个 Java 程序,使用 for 循环打印 X 星星图案。此 Java X 星图案示例在嵌套 for 循环中使用 if 条件进行迭代行。
package ShapePrograms;
import java.util.Scanner;
public class XPattern1 {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
System.out.print("Please Enter X Pattern Rows = ");
int rows = sc.nextInt();
System.out.println("---- Printing X Pattern of Stars ------");
int k = rows * 2 - 1;
for (int i = 1 ; i <= k; i++ )
{
for (int j = 1 ; j <= k; j++ )
{
if(j == i || j == k - i + 1)
{
System.out.print("*");
}
System.out.print(" ");
}
System.out.println();
}
}
}

在此 Java X 星图案 程序 中,我们用 while 循环 替换了 for 循环。
package ShapePrograms;
import java.util.Scanner;
public class XPattern2 {
private static Scanner sc;
public static void main(String[] args) {
int rows, j;
sc = new Scanner(System.in);
System.out.print("Please Enter X Pattern Rows = ");
rows = sc.nextInt();
System.out.println("---- Printing X Pattern of Stars ------");
int k = rows * 2 - 1;
int i = 1 ;
while( i <= k)
{
j = 1;
while (j <= k)
{
if(j == i || j == k - i + 1) {
System.out.print("*");
}
System.out.print(" ");
j++;
}
System.out.println();
i++;
}
}
}
Please Enter X Pattern Rows = 7
---- Printing X Pattern of Stars ------
* *
* *
* *
* *
* *
* *
*
* *
* *
* *
* *
* *
* *
Java 使用 do while 循环打印 X 星星图案的程序
package ShapePrograms;
import java.util.Scanner;
public class XPattern3 {
private static Scanner sc;
public static void main(String[] args) {
int rows, j;
sc = new Scanner(System.in);
System.out.print("Please Enter X Pattern Rows = ");
rows = sc.nextInt();
System.out.println("---- Printing X Pattern of Stars ------");
int k = rows * 2 - 1;
int i = 1 ;
do
{
j = 1;
do
{
if(j == i || j == k - i + 1) {
System.out.print("*");
}
System.out.print(" ");
j++;
} while (j <= k);
System.out.println();
i++;
}while( i <= k);
}
}
Please Enter X Pattern Rows = 9
---- Printing X Pattern of Stars ------
* *
* *
* *
* *
* *
* *
* *
* *
*
* *
* *
* *
* *
* *
* *
* *
* *
在此 Java 示例中,XPattern 函数打印给定符号的 X 图案。
package ShapePrograms;
import java.util.Scanner;
public class XPattern4 {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
System.out.print("Please Enter X Pattern Rows = ");
int rows = sc.nextInt();
System.out.print("Enter Character for X Pattern = ");
char ch = sc.next().charAt(0);
System.out.println("---- Printing X Pattern ------");
XPattern(rows, ch);
}
public static void XPattern(int rows, char ch) {
int k = rows * 2 - 1;
for (int i = 1 ; i <= k; i++ )
{
for (int j = 1 ; j <= k; j++ )
{
if(j == i || j == k - i + 1) {
System.out.print(ch);
}
System.out.print(" ");
}
System.out.println();
}
}
}
Please Enter X Pattern Rows = 10
Enter Character for X Pattern = #
---- Printing X Pattern ------
# #
# #
# #
# #
# #
# #
# #
# #
# #
#
# #
# #
# #
# #
# #
# #
# #
# #
# #