简体   繁体   English

通过在 main 方法中接受 integer 来打印树

[英]Print a tree by accepting an integer into the main method

I'm trying to print a tree by accepting an integer into the main method for an intro programming class.我正在尝试通过将 integer 接受为介绍编程 class 的主要方法来打印树。 If the number is positive, accept it.如果数字是正数,请接受。 If it is negative, print a statement and terminate the program.如果是否定的,打印一条语句并终止程序。

The program runs perfectly.该程序运行完美。 However, I am not allowed to print within the named method (printTriangle()).但是,我不允许在命名方法 (printTriangle()) 中打印。

What would the logical change in the order of code be to keep the printing statements solely in the main method()?将打印语句仅保留在 main method() 中的代码顺序的逻辑变化是什么?

I have provided the code and output below for your convenience.为了您的方便,我在下面提供了代码和 output。

Thanks!谢谢!

package triangletest;

import java.util.Scanner;

public class triangletest {

    public static void main(String[] args) {
        System.out.print("Enter the number of lines: ");

        Scanner scanner = new Scanner(System.in);

        int input = scanner.nextInt();

        scanner.close();

        if (input > 0) {
            printTriangle(input);
        } else {
            System.out.print("Number of lines is negative. Exiting");
        }
    }

    static void printTriangle(int input) {
        for (int i = 1, triangle = 1; i <= input; i++, triangle += 1) {
            for (int space = input; space > i; space--)
                System.out.print(" ");

            for (int x = 1; x <= triangle; x++)
                System.out.print("* ");

            System.out.println();
         }
    }
}

Output: Output:

Enter the number of lines: 
5

Just copy the code which is inside in the printTriangle method into the place where you call printTriangle method.只需将printTriangle方法中的代码复制到调用printTriangle方法的位置即可。

    public static void main(String[] args) {
        System.out.print("Enter the number of lines: ");
        Scanner scanner = new Scanner(System.in);
        int input = scanner.nextInt();
        scanner.close();
        if (input > 0) {
            for(int i = 1, triangle = 1; i <= input; i++, triangle += 1)
            {
                    for(int space = input; space > i; space--)
                        System.out.print(" ");
                    for(int x = 1; x <= triangle; x++)
                        System.out.print("* ");
                    System.out.println(); 
            }
        }
        else 
        {
            System.out.print("Number of lines is negative. Existing");
        }
    }

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

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