Java--for循环嵌套(打印用字符组成的各种图形)

//语句嵌套形式:其实就是语句中还有语句。
//循环嵌套
1、打印3行****

****
****
****
public class ForForDemo {
	public static void main(String[] args) {

		for (int x = 0; x < 3; x++)
		{
			for (int y = 0; y < 4; y++)
			{
				System.out.print("*");
			}
			System.out.println();
		}
	}
}

输出结果:

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

对于打印的结果可以看出:外层循环控制的是行数、内层循环控制的是每一行的列数,也就是一行中元素的个数。


2、打印

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

方法①

public class ForForDemo {
	public static void main(String[] args) {

		int z = 5;
		for (int x = 0; x < 5; x++)
		{
			for (int y = 0; y < z; y++)
			{
				System.out.print("*");
			}
			System.out.println();
			z--;
		}
	}
}

方法②

public class ForForDemo {
	public static void main(String[] args) {

		int z = 0;
		for (int x = 0; x < 5; x++)
		{
			for (int y = z; y < 5; y++)
			{
				System.out.print("*");
			}
			System.out.println();
			z++;
		}
	}
}

方法③(推荐用这种方法)

public class ForForDemo {
	public static void main(String[] args) {
		for (int x = 0; x < 5; x++)
		{
			for (int y = x; y < 5; y++)
			{
				System.out.print("*");
			}
			System.out.println();
		}
	}
}

3、打印依次递增的5行*

*
**
***
****
*****
public class ForForDemo {
	public static void main(String[] args) {
		for (int x = 0; x < 5; x++)
		{
			for (int y = 0; y <= x; y++)
			{
				System.out.print("*");
			}
			System.out.println();
		}
	}
}

4、打印

1
22
333
4444
55555
public class ForForDemo {
	public static void main(String[] args) {
		for (int x = 1; x < 6; x++)
		{
			for (int y = 1; y <= x; y++)
			{
				System.out.print(x);
			}
			System.out.println();
		}
	}
}

5、打印

1
12
123
1234
12345
public class ForForDemo {
	public static void main(String[] args) {
		for (int x = 1; x < 6; x++)
		{
			for (int y = 1; y <= x; y++)
			{
				System.out.print(y);
			}
			System.out.println();
		}
	}
}

6、打印

    * 
   * * 
  * * * 
 * * * * 
* * * * * 
public class Demo {
	public static void main(String[] args) {
		for(int x = 0; x < 5; x++)
		{
			for(int y = x+1; y < 5; y++)
			{
				System.out.print(" ");
			}
			for(int z = 0; z <= x; z++)
			{
				System.out.print("* ");
			}
			System.out.println();
		}
	}
}

你可能感兴趣的:(Java)