【问题标题】:Particular loop特定循环
【发布时间】:2010-12-09 07:00:58
【问题描述】:

嘿,我正在寻找一个接收这个数组的循环:

String[] arr = new String[3];
arr[0] = "one ";
arr[1] = "two ";
arr[2] = "three ";

然后输出:

one two three one one two two three three one one one two two two three three three

基本上,我希望它在每次迭代时将每个数组值的显示次数增加一。

【问题讨论】:

  • 这听起来像是一道作业题...尝试使用 Math.floor
  • 我认为你的意思是“new String[3];”
  • 你是如何实现它的?我的意思是你一定试过了。对吗?
  • 想想如果将一个 for 循环放入另一个循环会发生什么。
  • @Adeel Ansari 我很糟糕,后来我进入了线程 ^^ 可惜有人已经给出了答案,而不是 Ian 没有想到如何得到答案,并且会卡在他的下一个循环中写

标签: java for-loop iteration


【解决方案1】:
for (int i=1; i<=n; i++) {
    for (int j=0; j<3; j++) {
        for (int k=0; k<i; k++) {
            System.out.print(arr[j] + " ");
        }
    }
}

【讨论】:

    【解决方案2】:

    该代码将导致异常:您正在声明一个包含 2 个位置的数组并为其分配 3 个值。 arr[2] 将导致异常(超出范围)。

    使用嵌套循环打印内容。

    【讨论】:

    • OP提供的代码,初始化数组的代码。
    【解决方案3】:
      for(int i=0;i<Array.length;i++)
            {
                for(int j= 0 ;j<Array.length;j++)
                    {
                        for(int k=0;k<=i;k++)
                            {
                            System.out.println(""+Array[j]);
                             }
                    }
            }
    

    【讨论】:

      【解决方案4】:

      另一种方法:

      String[] array = {"One ","Two ", "Three "};
      int n = 10;
      int counter = 1;
      
              for(int i =0;i<n;i++){
                  for(int j=0;j<array.length;j++){
                      String element = array[j];
                      for(int k=0;k<counter;k++){
                          System.out.print(element+" ");
                      }
                  }
                  counter++;
                  System.out.println();
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-12
        • 2021-02-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多