钻石使用For循环 [英] Diamond Using For Loop

查看:107
本文介绍了钻石使用For循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用for循环根据用户输入来打印出菱形.我已经将它打印在菱形的右侧,但是无法将它打印在菱形的左侧.我尝试将我的代码反转无济于事.我在弄清楚使我的代码打印出整个菱形的逻辑时遇到了麻烦.预先感谢!

I am attempting to have a diamond print out based on user input using for loops. I've gotten it to print out the right side of the diamond but can't get it to print out the left side. I've tried reversing my code to no avail. I'm having trouble figuring out the logic to have my code print out an entire diamond. Thanks in advance!

如果num = 2的预期输出是(当然没有行):

The expected output if num=2 is (without the lines, of course):

 *
*$*
 *

到目前为止,这是我的代码:

Here's my code so far:

//Print out a diamond shape based on user input
for (int i=num; i>0; --i){
    System.out.print("*");
    for (int n=i; n<num; ++n){
        System.out.print("$*");
    }//Ending bracket of nested for loop
    System.out.println();
}//Ending bracket of for loop
//Print out a diamond shape based on user input
for (int i=0; i<num; ++i){
    System.out.print("*");
    for (int n=i; n<num; ++n){
        System.out.print("$*");
    }//Ending bracket of nested for loop
    System.out.println();
}//Ending bracket of for loop

推荐答案

基本上,您只需要添加另一个循环(一个循环用于上半部分,一个循环用于下半部分),就可以在每行中添加足够的空格,以便将钻石居中:

You basically only need to add another loop (one for the top half and one for the bottom half) in which you add enough spaces on each line in order to center the diamond:

for (int i=num; i>0; --i){
    //Insert spaces in order to center the diamond
    for (int n=0; n<i; ++n){
        System.out.print(" ");
    }
    System.out.print("*");
    for (int n=i; n<num; ++n){
        System.out.print("$*");
    }//Ending bracket of nested for loop
    System.out.println();
}//Ending bracket of for loop
//Print out a diamond shape based on user input
for (int i=0; i<=num; ++i){   //<= to print the last asterisk
    //Insert spaces in order to center the diamond
    for (int n=0; n<i; ++n){
        System.out.print(" ");
    }
    System.out.print("*");
    for (int n=i; n<num; ++n){
        System.out.print("$*");
    }//Ending bracket of nested for loop
    System.out.println();
}//Ending bracket of for loop

在您的示例中,我不确定num与钻石形状之间相关性的逻辑.我的代码为num = 1而不是num = 2打印所需的菱形.因此,在此代码中,num确定菱形的最大宽度($符号的数量).因此num = 2打印:

I'm not sure about the logic of the correlation between num and the shape of the diamond in your example. My code prints your desired diamond for num = 1 not num = 2. So in this code num determines the maximum width of the diamond (the number of $ signs). So num = 2 prints:

  *
 *$*
*$*$*
 *$*
  *

如果需要

 *
*$*
 *

(对于num=1等),您可以在上面的代码中用num-1替换每次出现的num.另外,您也可以添加行

for num=1 and so on, you can simply replace every occurence of num with num-1 in the code above. Alternatively, you could also just add the line

num--;

在代码之前,其余部分保持不变.

before the code and leave the rest as it is.

这篇关于钻石使用For循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆