题目:输出用 “*” 组成的 X 图案。
1、要求:
输入:多组输入,输入一个整数n表示输出的行数。
输出示例:n=5
2、分析:
- 由示例坐标图可看出,输出 * 的位置有两种情况:
1、i=j;(右对角线)
2、i+j=n-1;(左对角线)
在这些位置输出 * ,其余位置输出 空格,注意一行结束要给一个换行。
- 要求中的多次输入可以用一个while循环控制( while( sc.hasNextInt() ) )。
3、代码:
import java.util.Scanner;
public class TestDemo {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(sc.hasNextInt()){
int n= sc.nextInt();
for (int i = 0; i <n ; i++) {
for (int j = 0; j < n; j++) {
if(i==j){
System.out.print("*");
} else if(i+j==n-1){
System.out.print("*");
} else{
System.out.print(" ");
}
}
System.out.println();
}
}
}
}
//运行结果:
5
* *
* *
*
* *
* *
6
* *
* *
**
**
* *
* *
.....