Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/visual-studio-2010/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用单个for循环编写嵌套循环(通用)-java_Java - Fatal编程技术网

使用单个for循环编写嵌套循环(通用)-java

使用单个for循环编写嵌套循环(通用)-java,java,Java,在我的宿舍里,没有人知道如何在我们的CS作业中回答这个问题。它说: 嵌套循环 for(int i = 1; i <= height; i++) { for(int j = 1; j <= width; j++) { System.out.print("*"); } System.out.println(); } 宽度为4,高度为3。编写一个for循环 显示相同的矩形。记住,3和4只是 例如,您的代码必须是通用的,并且适用于任何宽度 和身高 我们尝

在我的宿舍里,没有人知道如何在我们的CS作业中回答这个问题。它说:

嵌套循环

for(int i = 1; i <= height; i++)
{
   for(int j = 1; j <= width; j++)
   {
      System.out.print("*");
   }
   System.out.println();
}
宽度为4,高度为3。编写一个for循环 显示相同的矩形。记住,3和4只是 例如,您的代码必须是通用的,并且适用于任何宽度 和身高


我们尝试了很多事情,但每一件都以失败告终。我们是否遗漏了一些明显的内容?

您应该查看需要显示的星号总数,并在迭代时适当显示星号/换行符(想想一行中有多少星号-不过我不想给您答案!)

您可以在for循环中使用多个条件

int w=0;
int w = 0;
for(int i = 0; i < height * width; i++)
{
   System.out.print("*");
   if( ++w >= width ) {
      w = 0;
      System.out.println();
   }
}
对于(int i=0;i<高度*宽度;i++) { 系统输出打印(“*”); 如果(++w>=宽度){ w=0; System.out.println(); } }
在我写的一篇文章中,这就是解决方案:

{set|($height)(3) ($width)(4)}

{for|i|1 : $i <= ($height*$width) : $i++|
   *
   {if| !(($i) % $width)|
      <br/>
   }
}
{set |($height)(3)($width)(4)}
{对于| i | 1:$i
int width=9;
整数高度=3;
for(int row=1,column=1;row
for(int row=0,column=0;(row
希望这有帮助


问候

我同意。给出HW答案是不好的。不过,只是一点提示:您可以使用%operator。。。
{set|($height)(3) ($width)(4)}

{for|i|1 : $i <= ($height*$width) : $i++|
   *
   {if| !(($i) % $width)|
      <br/>
   }
}
    int width = 9 ;
    int height = 3;
    for (int row = 1, column = 1 ; row <= height && column <= width; column++) {
        System.out.print("*");
        if(column == width) {
            column = 0;
            System.out.println();
            row ++;
        }
    }
for (int row = 0, column = 0; (row < height && column < width); column++)
{
  System.out.print("*");
  if (column == (width - 1))
  {
    column = -1;
    row++;
    System.out.println();
    continue;
  }
}