解决有趣的模式问题可以增强对循环的理解。它们是必不可少的,因为它们有助于建立对特定编程语言的坚实基础。有各种各样的模式,包括基于数字、基于星号和基于字母的模式。在本文中,我们将讨论一些java程序来打印有趣的星型模式。

声明并初始化一个指定行数和列数的整数“n”。
定义一个将运行到“n”的 for 循环。在此循环内定义一个 if-else 块。
if 块将在第一行和最后一行中打印星号“n”次,else 块将在第二行到第四行中打印空格“n/2”,表示 2 次和星号一次。
public class P1 {
public static void main(String[] args) {
int n = 5;
for(int i = 1; i <= n; i++) {
// till number of rows
if(i == 1 || i == n) {
for(int str = 1; str <= n; str++) {
System.out.print("*\t");
}
} else {
for(int spc = 1; spc <= n/2; spc++) {
System.out.print("\t");
}
for(int str = 1; str <= 1; str++){
System.out.print("*");
}
}
System.out.println();
// to move cursor to next line
}
}
}
* * * * * * * * * * * * *

声明并初始化一个指定行数的整数“n”。
创建一个嵌套的for循环,外部循环将运行到'n',内部循环将运行到空格的数量并打印空格。打印完后,我们将空格计数减1。
再次采用另一个内部 for 循环,该循环将运行到星星数并打印星星。打印后,我们会将星星计数增加 2。
public class P2 {
public static void main(String[] args) {
int n = 5;
int spc = n-1; // initial space count
int str = 1; // initial star count
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= spc; j++) { // spaces
System.out.print("\t");
}
spc--;
for(int k = 1; k <= str; k++) { // stars
System.out.print("*\t");
}
str += 2;
System.out.println();
}
}
}
* * * * * * * * * * * * * * * * * * * * * * * * *

声明并初始化一个指定行数的整数“n”。
定义嵌套的for循环,外层循环将从'n'到1运行,第一个内层循环将打印空格,第二个内层循环将打印星号。
public class P3 {
public static void main(String[] args) {
int n=5;
for(int i = n; i >= 1; i--) {
for(int spc = n-i; spc >= 1; spc--){ // spaces
System.out.print("\t");
}
for(int str = 1; str <= i; str++){ // stars
System.out.print("*\t");
}
System.out.println();
}
}
}
* * * * * * * * * * * * * * *

声明并初始化一个指定行数的整数“n”。
创建一个嵌套的 for 循环,外部循环将运行到“n”,第一个内部 for 循环将运行到空格数并打印空格。第二个将打印星星。
现在,采用 if-else 块,if 块将检查行号是否小于 3。如果小于,则执行 if 块以减少空间计数并增加星号计数。
如果行号大于2,则执行else块以增加空格计数并减少星号计数。
public class P4 {
public static void main(String[] args) {
int n = 5;
int spc = 2;
// initial space count
int str = 1;
// initial star count
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= spc; j++) {
// spaces
System.out.print("\t");
}
for (int j = 1; j <= str; j++) {
// stars
System.out.print("*\t");
}
if ( i <= 2) {
spc--;
str += 2;
} else {
spc++;
str -= 2;
}
System.out.println();
}
}
}
* * * * * * * * * * * * *

声明并初始化一个指定行数的整数“n”。
定义嵌套的 for 循环,外部循环将运行到“n”,第一个内部循环将打印空格,第二个内部循环将打印星星。
public class P5 {
public static void main(String[] args) {
int n = 5;
for(int i = 1; i <= n; i++){
for(int spc = 1; spc <= n-i; spc++) {
System.out.print("\t");
}
for(int str = 1; str <= i; str++) {
System.out.print("*\t");
}
System.out.println();
}
}
}
* * * * * * * * * * * * * * *
在本文中,我们讨论了有趣的星形图案的问题。这些模式解决方案将帮助您解码模式问题的逻辑,并使您能够自己解决其他模式。
以上就是打印有趣图案的程序的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号