如何使用循环显示图案 [英] How to display patterns using loops

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

问题描述

我有以下问题:
使用显示以下模式的嵌套循环

I have below question:
Use nested loops that display following patterns

  *
 ***
*****
 ***
  *



我尝试过的事情:



What I have tried:

for (int i = 0; i < 5; i++) {
    for (int j = 0; j <= i * 2; j++) {
         System.out.print("*");
	}
         System.out.println();
	}

推荐答案

public class Diamond
{
  public static void main( String args[] )
  {
    int N = Integer.parseInt(args[0]);
    int row, col;
    for (row=-N; row<=N; ++row)
    {
      for (col=-N; col<=N; ++col)
      {
        char c = Math.abs(col) + Math.abs(row) <= N ? '*' : ' ';
        System.out.print(c);
      }
      System.out.println();
    }
  }
}


如果您无法一次处理钻石,可以将其视为两个背对背的三角形.
您的代码缺少行首的空格.

我们不做您的家庭作业.
家庭作业并非旨在测试您乞求他人完成工作的技能,而是可以让您思考并帮助您的老师检查您对所修课程的理解以及在应用这些课程时遇到的问题.
您的任何失败都会帮助您的老师发现您的弱点并采取补救措施.
您的任何失败都会帮助您学习什么有效,什么无效,这被称为试错"学习.
因此,请尝试一下,重新阅读您的课程并开始工作.如果您遇到特定问题,请显示代码并解释这个确切的问题,我们可能会提供帮助.

作为程序员,您的工作是创建解决特定问题的算法,您不能依靠别人永远为您完成任务,因此有时您必须学习如何.而且越早越好.
当您只是寻求解决方案时,这就像试图通过培训其他人来学习驾驶汽车.
创建算法基本上是在寻找数学并进行必要的调整以适合您的实际问题.

[更新]
有趣的链接:
stanford.edu:学习编程 [
If you can''t handle the diamond at once, think of it as 2 triangles back to back.
your code is missing the spaces at beginning of lines.

We do not do your HomeWork.
HomeWork is not set to test your skills at begging other people to do your work, it is set to make you think and to help your teacher to check your understanding of the courses you have taken and also the problems you have at applying them.
Any failure of you will help your teacher spot your weaknesses and set remedial actions.
Any failure of you will help you to learn what works and what don''t, it is called ''trial and error'' learning.
So, give it a try, reread your lessons and start working. If you are stuck on a specific problem, show your code and explain this exact problem, we might help.

As programmer, your job is to create algorithms that solve specific problems and you can''t rely on someone else to eternally do it for you, so there is a time where you will have to learn how to. And the sooner, the better.
When you just ask for the solution, it is like trying to learn to drive a car by having someone else training.
Creating an algorithm is basically finding the maths and make necessary adaptation to fit your actual problem.

[Update]
Interesting link:
stanford.edu: Learn to Program[^]


这就是答案
This is the answer
for (int i = 1; i < 5; i += 2) {
			for (int j = 0; j < 4 - i / 2; j++)
				System.out.print(" ");

			for (int j = 0; j < i; j++)
				System.out.print("*");

			System.out.println();
		}

		for (int i = 5; i > 0; i -= 2) {
			for (int j = 0; j < 4 - i / 2; j++)
				System.out.print(" ");

			for (int j = 0; j < i; j++)
				System.out.print("*");

			System.out.println();
		}


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

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