嵌套循环并增加用户输入

时间:2016-02-23 22:44:33

标签: java loops for-loop while-loop nested

我正在尝试打印用户输入数字并按该数量的空格缩进。我似乎无法将数字缩进,但是,我可以垂直打印它们。有帮助吗?这是我的代码。

 for (i = 0; i <= userNum; i++) {
      for (j = 0; j < i; j++) {
          System.out.println(i);
          break;

如果用户输入数字3,我的输出目前看起来像这样:

1
2
3

什么时候看起来像这样:

   1
    2
     3

5 个答案:

答案 0 :(得分:3)

这应该这样做

test_term, category, SAAS~All Products~pcmcat367
test_term, features, ~ENERGY STAR
test_term, brand_facet, Brand~GE

答案 1 :(得分:1)

您可以尝试在for循环中添加另一个for循环。 print语句将在此嵌套for循环之后。内循环将从零开始到i + 1。在此for循环中,您可以打印空格或制表符。然后在for循环后,您可以打印数字。确保内部for循环中的print语句中没有包含新行。

答案 2 :(得分:1)

您尚未添加代码以添加缩进。试试这个:

<script src="jwplayer/jwplayer.flash.swf"></script>

用以下方式调用:

public static void printNum(int userNum) {
    for (int i = 0; i < userNum; i++) {
        System.out.print(" ");
    }
    System.out.print(userNum+ "\n");
}

给出以下内容:

printNum(10);
printNum(1);
printNum(2);
printNum(3);

答案 3 :(得分:0)

public class Program {

    public static void main(String[] args) {
        int i = 3; // or your userNum
        // this loop will iterates through 1 to i (or 1 to userNum for you)
        for (int j = 1; j <= i; j++) {
            // this loop iterates until j2 equals j (e.g. if j = 5, this loop will iterates 4 times)
            for (int j2 = 1; j2 < j; j2++) {
                // prints the space(s)
                System.out.print(" ");
            }
            // prints the current number (in the first loop) and line break
            System.out.println(j);
        }
    }
}

答案 4 :(得分:0)

我希望这能解决你的问题:

for (i = 1; i <= userNum; i++)
      System.out.format("%+(i-1)+s]%n", i);
相关问题