沙漏模型

1、题目地址

https://pintia.cn/problem-sets/17/problems/260

2、题目条件

输入格式:
输入在一行给出1个正整数N(≤1000)和一个符号,中间以空格分隔。

输出格式:
首先打印出由给定符号组成的最大的沙漏形状,最后在一行中输出剩下没用掉的符号数。

输入样例:
19 *

3、代码

import java.util.Scanner;
public class sand {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int count = 0;
        String tag = "";
        try {
          while (in.hasNext()) {
            count = in.nextInt();
            tag = in.next();

            break;
          }
        } catch (NullPointerException ex) {
        
        }
        sand(count,tag);
    
    }
    
    public static void sand( int count , String tag) {
        int tempCount = 0;
        int tempRows = 0;
        int max = 0;
        int outPutCount = 0;
        for( int i = 1 ; tempCount <= count+1 ; i++ ) {
            max = (2*i-1);
            tempCount += max*2;
            tempRows = i;
        }

        if( count > 1) {
            tempRows -=1;
            max-=2;
        }
        
        for( int i =0; i< tempRows-1 ; i++) {
            
            for( int j = 0 ; j < i ; j++) {
                System.out.print(" ");
            }
            for( int j = 0 ; j < max-2*i ; j++) {
                System.out.print(tag);
                outPutCount++;
            }

            System.out.println();
            
        }
        
        for( int i = tempRows; i >0  ; i--) {
            
            for( int j = 1 ; j < i ; j++) {
                System.out.print(" ");
            }
            for( int j = 0 ; j < max-2*(i-1) ; j++) {
                System.out.print(tag);
                outPutCount++;
            }

            System.out.println();
        }
        
        System.out.print(count-outPutCount);    
    }
}

4、问题及总结

  1. 输出格式问题
    输出格式在正常输出的符号后,增加了多余空格,导致结果检查通不过,报格式错误。
  2. 最小值问题
    本机编写代码时没有关注边界问题,这里是简单对边界添加了保护。
  3. 数学公式
    这里没有使用数学公式,是自己计算的行数,有参考其他人做法,使用java数学公式更为简单。
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、Python简介和环境搭建以及pip的安装 4课时实验课主要内容 【Python简介】: Python 是一个...
    _小老虎_阅读 11,131评论 0 10
  • 不知不觉,岁寒输入法的更新历史已经可以列出这么一长串来了。从中可以看出,岁寒的发展过程也是一个不断试错的过程,其中...
    临岁之寒阅读 34,420评论 1 6
  • 官网 中文版本 好的网站 Content-type: text/htmlBASH Section: User ...
    不排版阅读 9,947评论 0 5
  • 我们习惯把人生分为这样几个阶段,幼年、童年、青年、中年和老年。但奇怪的是,我们总是模式化的去向青春致敬,有...
    半城烟沙小确幸阅读 1,553评论 1 1
  • 动画短片《In the Fall》,仅仅只有100秒的时间,但是给我们讲解了一个发人深省的故事。一个中年男子在楼上...
    缓存_ed72阅读 5,205评论 0 0