chr*_*ris 0 java for-loop spacing
我正在编写Java类中的程序,我需要打印一个星形金字塔.我的代码是:
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number between 1 and 20: ");
int value = sc.nextInt();
System.out.println("Pattern B: ");
for(int x = 1; x <= value; x++){
for(int y = value; y>=x; y-- ){
System.out.print("*");
}
System.out.print("\n");
}
Run Code Online (Sandbox Code Playgroud)
我的结果打印出一行5星,然后是4,3,2,1(如果用户输入数字5).我想要的是将星星都推到右边.如:
一行5星,(空格)行4星,(两个空格)行3星,(三个空格)行2星,(四个空格)行一星
我有道理吗?
我应该引入if then语句,检查变量y并相应地增加空格吗?如果我让你困惑,我很抱歉.
你可以做以下两件事之一:
for在循环内部引入另一个循环x for,循环x次数,print x空格字符或ORy for循环,从运行1通过value,然后添加一个if语句中,以决定是否打印空格或*.| 归档时间: |
|
| 查看次数: |
5000 次 |
| 最近记录: |