知识点
💖要弄清楚行数row,空格space,星星star之间的关系;
一.直角三角形(左上左下右上右下,都有图)
1.1打印直角三角形(左上)
/**打印直角三角形
*
**
***
****
*****
如上图
*/
class DemoXing2 {
public static void main(String[] args) {
//打印行数row
for(int row=1;row<=5;row++){
//打印星星
for(int star=0;star <row ;star++){
System.out.print("*");
}
//换行
System.out.println();
}
}
}
1.2打印倒直角三角形(左下)
/**打印倒直角三角形
*****
****
***
**
*
如上图
*/
class DemoXing3 {
public static void main(String[] args) {
//打印行数row
for(int row=1;row<=5;row++){
//打印星星
for(int star=5;star>=row ;star--){
System.out.print("*");
}
//换行
System.out.println();
}
}
}
1.3打印直角三角形(右上)
/*打印三角形
*
**
***
****
*****
如上图
*/
class DemoXing4{
public static void main(String[] args) {
//打印行数5
for(int row=1;row<=5;row++){
//打印空格
for(int space=1; space<=5-row;space++){
System.out.print(" ");
}
//打印星星
for(int star=1;star<=row;star++){
System.out.print("*");
}
//换行
System.out.println();
}
}
}
1.4打印直角三角形(右下)
/**打印如图三角形
*****
****
***
**
*
如上图
*/
class DemoXing7{
public static void main(String[] args) {
for(int row =1;row<=5;row++)
{
for(int space=0;space<=row-1;space++)
{
System.out.print(" ");
}
for(int star=5;star >= row;star--)
{
System.out.print("*");
}
System.out.println();
}
}
}
💖二.打印等腰三角形
2.1正等腰三角形
/*打印等腰三角形
*
***
*****
*******
例如上图
*/
class DemoXing {
public static void main(String[] args) {
//打印行数row
for(int row=1;row<=4;row++){
//打印空格
for(int space=1; space <= 4-row;space++){
System.out.print(" ");
}
//打印星星
for(int star=1;star <= 2*row -1;star++){
System.out.print("*");
}
//换行
System.out.println();
}
}
}
2.2打印用户输入指定行数的等腰三角形
/*打印用户输入指定行数的等腰三角形
*/
import java.util.Scanner;
class DemoXing1{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
for(;;){
System.out.println("请输入行数");
int rows = scanner.nextInt();
//打印行数
for(int row = 1; row <= rows; row++){
//打印空格
for(int space = 1; space <= rows - row; space++){
System.out.print(" ");
}
//打印星星
for(int star = 1; star <= 2*row -1;star++){
System.out.print("*");
}
//换行
System.out.println();
}
//给用户提示是否继续输入? y/n
System.out.println("是否继续打印?y/n");
//接收用户输入的是y还是n
String selection = scanner.next();
if("y".equals(selection)){
//继续打印三角形 continue
continue;
}else{
//不打印,退出循环 break:退出本层循环
break;
}
}
}
}