zoukankan      html  css  js  c++  java
  • java中的for嵌套(一个好例子)

    (1)常规的大星

    *****

    *****

    *****

    *****

    上面的java程序为

     1 public class daxing {
     2 
     3     public static void main(String[] args) {
     4 
     5         for (int i = 0; i < 5; i++) {
     6             for (int j = 0; j < 5; j++) {
     7                 System.out.print("*");
     8             }
     9             System.out.println();
    10         }
    11 
    12     }
    13 
    14 }
    View Code

    (2)

    *****

    ****

    ***

    **

    *

    上面程序打印代码为

    方法一

     1 public class daxing {
     2 
     3     public static void main(String[] args) {
     4 
     5         int z = 5;
     6         for (int i = 0; i < 5; i++) {
     7             for (int j = 0; j < z; j++) {
     8                 System.out.print("*");
     9             }
    10             System.out.println();
    11             z--;
    12         }
    13     }
    14 }
    View Code

    方法二:(优化一下)

     1 public class daxing {
     2 
     3     public static void main(String[] args) {
     4 
     5         int z = 0;
     6         for (int i = 0; i < 5; i++) {
     7             for (int j = z; j < 5; j++) {
     8                 System.out.print("*");
     9             }
    10             System.out.println();
    11             z++;
    12         }
    13     }
    14 }
    View Code

    方法三:(再优化一下)

     1 public class daxing {
     2 
     3     public static void main(String[] args) {
     4 
     5         
     6         for (int i = 0; i < 5; i++) {
     7             for (int j = i; j < 5; j++) {
     8                 System.out.print("*");
     9             }
    10             System.out.println();
    11         }
    12     }
    13 }
    View Code
  • 相关阅读:
    python 单下划线/双下划线使用总结
    error connection reset by peer 104
    变形课
    求并联电阻值
    HDU2054:A == B ?
    Do the Untwist
    开门人和关门人
    关于HEXO安装失败的解决方法
    代码高亮显示——google-code-prettify
    网站图标——favicon
  • 原文地址:https://www.cnblogs.com/sxmcACM/p/3452888.html
Copyright © 2011-2022 走看看