zoukankan      html  css  js  c++  java
  • 算法笔记_223:打印回型嵌套(Java)

    目录

    1 问题描述

    2 解决方案

     


    1 问题描述

    ***********
    *         *
    * ******* *
    * *     * *
    * * *** * *
    * * * * * *
    * * *** * *
    * *     * *
    * ******* *
    *         *
    ***********
    
    观察这个图形,它是由一系列正方形的星号方框嵌套而成。
    在上边的例子中,最外方框的边长为11。
    
    本题的任务就是从标准输入获得一个整数n(1<n<100)
    程序则生成嵌套着的回字型星号方框。其最外层方框的边长为n
    
    例如:
    输入:
    5
    程序输出:
    *****
    *   *
    * * *
    *   *
    *****
    
    输入:6
    程序输出:
    ******
    *    *
    * ** *
    * ** *
    *    *
    ******

    2 解决方案

     1 import java.util.Scanner;
     2 
     3 public class Main {
     4     
     5     public void getResult(int n) {
     6         char[][] value = new char[n][n];
     7         for(int i = 0;i < n;i++)
     8             for(int j = 0;j < n;j++)
     9                 value[i][j] = ' ';
    10         for(int i = 0;i < n;i = i + 2) {
    11             int start = i, end = n - i;
    12             if(end < start)
    13                 break;
    14             for(int j = start;j < end;j++) {
    15                 value[i][j] = '*';   
    16                 value[j][i] = '*';
    17                 value[end - 1][j] = '*';
    18                 value[j][end - 1] = '*';
    19             }
    20         }
    21         for(int i = 0;i < n;i++) {
    22             for(int j = 0;j < n;j++)
    23                 System.out.print(value[i][j]);
    24             System.out.println();
    25         }
    26     }
    27     
    28     public static void main(String[] args) {
    29         Main test = new Main();
    30         Scanner in = new Scanner(System.in);
    31         int n = in.nextInt();
    32         test.getResult(n);
    33     }
    34 }

    运行结果:

    13
    *************
    *           *
    * ********* *
    * *       * *
    * * ***** * *
    * * *   * * *
    * * * * * * *
    * * *   * * *
    * * ***** * *
    * *       * *
    * ********* *
    *           *
    *************
  • 相关阅读:
    array and ram
    char as int
    pointer of 2d array and address
    Install SAP HANA EXPRESS on Google Cloud Platform
    Ubuntu remount hard drive
    Compile OpenSSL with Visual Studio 2019
    Install Jupyter notebook and tensorflow on Ubuntu 18.04
    Build OpenCV text(OCR) module on windows with Visual Studio 2019
    Reinstall VirtualBox 6.0 on Ubuntu 18.04
    Pitfall in std::vector<cv::Mat>
  • 原文地址:https://www.cnblogs.com/liuzhen1995/p/6894729.html
Copyright © 2011-2022 走看看