Java程序打印左三角形星号图案
在这篇文章中,我们将学习如何使用Java打印左三角形星号图案。该图案是使用多个for循环和print语句形成的。
问题陈述
编写一个Java程序来打印左三角形星号图案。以下是演示:
输入
Enter the number of rows : 8
输出
The right triangle star pattern :
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
不同的方法
以下是使用Java打印左三角形星号图案的步骤:
使用预定义输入
以下是打印左三角形星号图案的步骤:
- 定义一个整数变量来表示行数。
- 使用嵌套for循环来打印左三角形图案中每一行的空格和星号。
示例
这里,整数已预先定义,其值被访问并显示在控制台上:
public class RightTriangle{
public static void main(String args[]){
int i, j, my_input;
my_input = 8;
System.out.println("The number of rows is defined as " +my_input);
System.out.println("The right triangle star pattern : ");
for (i=0; i<my_input; i++){
for (j=2*(my_input-i); j>=0; j--){
System.out.print(" ");
}
for (j=0; j<=i; j++ ){
System.out.print("* ");
}
System.out.println();
}
}
}
输出
The number of rows is defined as 8
The right triangle star pattern :
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
使用用户定义输入
以下是打印左三角形星号图案的步骤:
- 从java.util包导入Scanner类以接受用户输入。
- 创建一个Scanner对象,并提示用户输入行数。
- 使用**嵌套for循环**来控制每一行打印的行数、空格和星号。
示例
这里,输入是基于提示由用户输入的:
import java.util.Scanner;
public class RightTriangle{
public static void main(String args[]){
int i, j, my_input;
System.out.println("Required packages have been imported");
Scanner my_scanner = new Scanner(System.in);
System.out.println("A reader object has been defined ");
System.out.print("Enter the number of rows : ");
my_input = my_scanner.nextInt();
System.out.println("The right triangle star pattern : ");
for (i=0; i<my_input; i++){
for (j=2*(my_input-i); j>=0; j--){
System.out.print(" ");
}
for (j=0; j<=i; j++ ){
System.out.print("* ");
}
System.out.println();
}
}
}
输出
Required packages have been imported
A reader object has been defined
Enter the number of rows : 8
The right triangle star pattern :
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP