简体   繁体   English

如何在Java中的命令行中打印十字形?

[英]How to print a cross shape in command line in Java?

I have to create a cross shape using methods, and the parameter is the 'size' of the cross. 我必须使用方法创建十字形,参数是十字的“大小”。 A number is input and the cross is drawn if the number is odd, so if I were to input a 5, the output would look like the screenshot I added to the bottom 输入数字并在数字为奇数的情况下绘制十字,因此,如果我输入5,输出将类似于我添加到底部的屏幕截图

The centre line is what's really throwing me off as I've only started methods last week, but so far I have: 中心线真正让我失望的是,我上周才开始使用方法,但到目前为止,我有:

import java.util.Scanner;

public class Cross {

    public static void main(String[] arg) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Please type a number: ");
        int num = keyboard.nextInt(); 
        drawCross(num);
    }

    public static void drawCross(int num){
        for (int = 1; i <= num; i++) {
            if ((num % 2) != 0) {
                System.out.println(i + "*");
            }
        }
    }

}

I know this is probably way off, but I'm a total newbie to methods. 我知道这可能还很遥远,但是我是方法的新手。

截图:

Analyze the problem before you start programming. 在开始编程之前,分析问题。 Break the task into steps: 将任务分为以下步骤:

  1. Check whether num is valid for this problem. 检查num是否对这个问题有效。
    • num must be positive. num必须为正。
    • num must be odd. num必须是奇数。
    • Notice that you're checking whether num is valid more than once. 请注意,您正在检查num是否有效多次。 Check it at the beginning, and quit with an error message if num is invalid. 首先检查它,如果num无效,则退出并显示错误消息。 Or, throw an exception, and have main catch it and report to the user. 或者,抛出异常,并让main捕获该异常并报告给用户。
      • After you know how to use exceptions, that is. 在您知道如何使用异常之后。
    • By the way, num is a bad name for the variable. 顺便说一句, num对于变量来说是个坏名字。 It's too generic. 这太笼统了。 Except for loop indices, try to have your name be descriptive. 除循环索引外,请尝试使用描述性名称。
  2. Compute how many spaces must precede the * on all but the center output line. 计算除中心输出线外的所有*之前必须有多少空格。
  3. Compute which line is the center output line. 计算哪条线是中心输出线。
  4. Do a loop for the top half of the output. 对输出的上半部分执行循环。
    • Don't use System.out.println() for individual characters. 不要将System.out.println()用于单个字符。
    • That method should be called only once per line. 每行只能调用一次该方法。
  5. Print the central line. 打印中心线。
  6. Do a loop for the bottom half of the output. 对输出的下半部分进行循环。

Now, you should try to stop doing everything in main and other static methods. 现在,您应该尝试停止使用main和其他静态方法进行所有操作。 Cross is a class, and you should create an instance of the class and have it do the work. Cross是一个类,您应该创建该类的实例并使其工作。

public class Cross {
    public static void main(String[] arg) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Please type a number: ");
        int num = keyboard.nextInt();
        Cross cross = new Cross();
        cross.drawCross(num);
    }

    private void drawCross(int size) {
        // Your turn.
    }
}

Why? 为什么? So you can test it. 这样就可以对其进行测试。 One of the most invaluable tools in Java programming is the JUnit library. Java编程中最有价值的工具之一是JUnit库。 You will want to offload your logic into tiny methods like: 您将需要将逻辑卸载到微小的方法中,例如:

public boolean validSize(int size) {
    // You fill this in.
}

In a test class, CrossTest , you'll write code like: 在测试类CrossTest ,您将编写如下代码:

@Test
public void negativeSizesAreIllegal() {
    Cross cross = new Cross();
    // Test whether cross.validSize(-13) returns false.
    // Look at the JUnit web site or any book describing the tool.
}

Figure out what your requirements on the method are, and write tests to check each one. 弄清楚您对方法的要求,并编写测试以检查每个要求。 You'll have similar tests too for 0, odd integers, and even integers. 您还将对0,奇数甚至偶数进行类似的测试。 But if you do all your code in static methods, that's a lot harder. 但是,如果您以静态方法执行所有代码,则要困难得多。 This way, as you change your program, you'll know whether your changes have broken your tests. 这样,在更改程序时,您将知道所做的更改是否破坏了测试。 It's like computing an indefinite integral, and differentiating it to check whether you made a mistake. 这就像计算一个不确定的积分,并对其进行微分以检查您是否犯了错误。

Finally, simplify your work. 最后,简化您的工作。 The way I outlined your problem, there will be a lot of code duplication. 我概述问题的方式将有很多代码重复。 See if you can write a method to replace the duplicate code in steps 4 and 6, and call it twice. 查看是否可以在步骤4和步骤6中编写替换重复代码的方法,并调用两次。 Keep going with it; 继续前进; you'll see lots of chances to shorten your program. 您会发现很多缩短程序的机会。 Having tests is invaluable for that. 为此,进行测试非常宝贵。 You'll also be able to use standard methods in the java.lang.String class to simplify things further. 您还可以在java.lang.String类中使用标准方法来进一步简化操作。

Did you see that 你看见了吗

System.out.println(i + "*");

did not do what you thought it did? 没有按照您的想法做?

Not a best solution. 不是最佳解决方案。 but this one I came up with in 2 mins time : 但是我在2分钟内想到了这个:

public static void drawCross(int num){
    if (num % 2 != 0)  {
     for(int i = 0; i < num; i++) {
            for(int j = 0; j < num; j++) {
                if((i == num / 2) || (j == num / 2)) 
                    System.out.print("*");
                else 
                    System.out.print(" ");
            }
            System.out.println();
        }
    }
}

Here is some code that should work: 这是一些应该起作用的代码:

public static void drawCross(int num)
{
    if(num % 2 != 0) //if "num" is odd
    {
        for(int y = 0; y < num; y++) //loop through the following code "num" times
        {
            for(int x = 0; x < num; x++) //loop through the following code "num" times
            {
                if(x == (int)(num / 2) || y == (int)(num / 2)) //if "x" or "y" is in the middle
                    /*(note that at this point "num" will always be odd, so "num / 2" will always 
                    be #.5. That's why the "(int)" is there: to change it from "#.5" to "#"*/
                {
                    System.out.print("*"); //print "*"
                }
                else //if "x" or "y" is NOT in the middle
                {
                    System.out.print(" "); //print a space
                }
            }
            System.out.println(); //create a new line
        }
    }
}
public static void drawCross(int num){
    if(num % 2 != 0){
        for(int line = 0;line < num;line++){
            for(int col = 0;col < num;col++){
                if(line == num / 2 || col == num / 2) System.out.print("*");
                else System.out.print(" ");
            }
            System.out.println("");
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM