Group Programming Algorithm Ladder Competition L1-015 Drawing squares with Obama (15 points) (Java)

The topics are as follows:

U.S. President Obama not only called on everyone to learn programming, but even set an example by writing code, becoming the first president in U.S. history to write computer code. At the end of 2014, to celebrate the official launch of Computer Science Education Week, Obama wrote a very simple computer code: draw a square on the screen. Now you can paint with him too!

Input format:

Enter a line that gives the side length of the square N (3≤N≤21) and some characters that make up the side of the square C, separated by a space.

Output format:

COutputs the square drawn by the given characters . But notice that the row spacing is larger than the column spacing, so in order to make the result look more square, the number of rows we output is actually 50% of the number of columns (rounded up).

Input example:

10 a

Output sample:

aaaaaaaaaa
aaaaaaaaaa
aaaaaaaaaa
aaaaaaaaaa
aaaaaaaaaa

My classmate asked me to do something that looks complicated but is actually relatively simple.

Looking at the question, the information that can be brought to us is nothing more than  the range of side length N (3≤N≤21) plus some kind of characters that form the side of the square C, separated by a space,   followed by the number of rows in the output, which is actually the number of columns. 50% (rounded up) look at the code:


import java.util.Scanner;

public class LadderRace {
    public static void main(String[] args) {
        code();
    }
    public static void code() {
       /**
         * Java api 中的 Math.round()方法
         */
        Scanner sc = new Scanner(System.in);
        int columnVal = sc.nextInt();
        String LineVal = sc.nextLine();
        /**
         * 这里科普一个基础   在java中 当被除数是奇数时只取整数部分
         * 例如9/2 结果会是4  要改变这种情况,需要把至少其中之一操作数变成浮点数,如9.0/2或9/2.0或9.0/2.0等等
         */
        // 外层控制行 内层控制列
        // 条件那里也可以用Math.round(columnVal/2.0) 为什么用2.0请看上面
        for (int i = 1; i <= Math.round(columnVal % 2 == 1 ? columnVal / 2 + 1 : columnVal / 2); i++) {
            for (int j = 1; j <= columnVal; j++) {
                //trim()  去空格
                System.out.print(LineVal.trim());
            }
            //走完一行换行
            System.out.println();
        }
    }
}

I have provided two methods above

(1) One is to change the divisor into a floating point type 

(2) The second is to judge based on the remainder 

Let’s look at the results:

 Okay, if there is anything you don’t understand, you can send me a private message. See you next time~~~

Guess you like

Origin blog.csdn.net/qq_45104282/article/details/128241163